Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

jquery - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...