JavaScript中的货币数学 [英] Currency Math in JavaScript
问题描述
有人可以帮我解决这个算术问题的JavaScript / jQuery解决方案:
Can someone please help me out with a JavaScript/jQuery solution for this arithmetic problem:
我需要从另一个中减去一个数字。
I need to subtract one number from the other.
问题是数字有一个美元符号(因为它的钱),因此jQuery将它们视为字符串而不是数字。
The problem is that the numbers have a dollar sign (because its money), therefore jQuery is treating them as strings instead of numbers.
我创建了两个变量 - toalAssets
和 totalLiabilites
。我想从前者中减去后者并将结果放入另一个名为 netWorth
的变量中。
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
.
也许我需要使用 parseFloat()
?
但我不知道怎么回事 - 这一切都在我头上!
But I'm not sure how - This is all a little over my head!
推荐答案
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
注意:在JavaScript中,建议 1 将货币处理为表示分数(8512而不是85.12)的整数。这是为了避免浮点运算的问题。 0.1 + 0.2 == 0.3
在JavaScript中返回false,但幸运的是浮点中的整数运算是精确的,因此可以通过缩放来避免十进制表示错误。
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.
您可能需要查看以下帖子以进一步阅读此主题: JavaScript的数学是否被破坏?
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.
1 Douglas Crockford: JavaScript:好的部件:附录A - 可怕的部件(第105页)。
这篇关于JavaScript中的货币数学的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!