JavaScript: Currency math (add, subtract, multiply, division etc.)
JavaScript Math: Exercise-25 with Solution
Write a JavaScript function to do currency math (add, subtract, multiply, divide etc.).
Test Data :
n1 = '$40.24', n2 = '$21.57';
Sample Solution:-
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Write a JavaScript function to make currency math (add, subtract, multiply, division etc.).</title>
</head>
<body>
</body>
</html>
JavaScript Code:
var n1 = '$40.24';
var n2 = '$21.57';
var regp = /[^0-9.-]+/g;
console.log(parseFloat(n1.replace(regp, '')) + parseFloat(n2.replace(regp, '')));
console.log(parseFloat(n1.replace(regp, '')) - parseFloat(n2.replace(regp, '')));
console.log(parseFloat(n1.replace(regp, '')) * parseFloat(n2.replace(regp, '')));
console.log(parseFloat(n1.replace(regp, '')) / parseFloat(n2.replace(regp, '')));
Sample Output:
61.81 18.67 867.9768 1.865554010199351
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-math-exercise-25 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript function to round a number to a specified number of digits and strip extra zeros (if any).
Next: Write a JavaScript function to calculate the nth root of a number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join