Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Currency Math in JavaScript

Can someone please help me out with a JavaScript/jQuery solution for this arithmetic problem:

I need to subtract one number from the other.

The problem is that the numbers have a dollar sign (because its money), therefore jQuery is treating them as strings instead of numbers.

I have created two variables - toalAssets and totalLiabilites. I would like to subtract the latter from the former and place the result into another variable called netWorth.

Perhaps i need to use parseFloat()?

But I'm not sure how - This is all a little over my head!

like image 898
swisstony Avatar asked Mar 31 '10 20:03

swisstony


People also ask

How to handle monetary values in JavaScript?

How to do this? We have to add two values 0.2 and 0.1, if we do it directly with JS we already know that there will be problems. 1) Multiply each value by 100: (0.2 * 100 + 0.1 * 100) = 30 cents. 2) Recover the value to money: (0.2 * 100 + 0.1 * 100) / 100 = 0.3.

What is js currency?

currency. js is a lightweight ~1kb javascript library for working with currency values. It was built to work around floating point issues in javascript.

How do you format numbers in JavaScript?

JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl. NumberFormat() method to format the number with currency.


1 Answers

var totalLiabilites = '$52.34';
var toalAssets      = '$85.12';
var pattern         = /[^0-9.-]+/g;

var result = parseFloat(toalAssets.replace(pattern, '')) -
             parseFloat(totalLiabilites.replace(pattern, ''));

// result: 32.78

Note: In JavaScript it is recommended1 to handle money as an integer representing the number of cents (8512 instead of 85.12). This is to avoid problems with floating-point arithmetic. 0.1 + 0.2 == 0.3 returns false in JavaScript, but fortunately integer arithmetic in floating point is exact, so decimal representation errors can be avoided by scaling.

You may want to check the following post for further reading on this topic: Is JavaScript’s math broken?

You can always apply the currency-sign formatting when the values are rendered to the browser.


1Douglas Crockford: JavaScript: The Good Parts: Appendix A - Awful Parts (page 105).

like image 86
Daniel Vassallo Avatar answered Oct 19 '22 00:10

Daniel Vassallo