简体   繁体   English

如何在Javascript中添加美元金额

[英]How do I add to dollar amounts in Javascript

I simply want to add to numbers (currency if you will) like 1.5 and 1.47 together and have it equal 1.97. 我只想添加数字(货币,如果你愿意),像1.5和1.47一样,并使它等于1.97。

How is this accomplished? 这是如何完成的? I did not know I did not know how to do this! 我不知道我不知道怎么做! :) :)

var discountAmount = 0;
var ogCookie = < %= strJsonCookie % >
for (var i = 0; i < ogCookie.products.length; i++) {
    discountAmount = parseFloat(discountAmount) + parseFloat(ogCookie.products[i].discount_amount);
}
alert(discountAmount);

使用parseFloat而不是parseInt

 parseFloat("1.19") + parseFloat("2.82") == 4.01

As others have mentioned, you should use parseFloat instead of parseInt . 正如其他人所提到的,你应该使用parseFloat而不是parseInt However, due to precision issues it's likely you will also need to use .toFixed(2) when you display the result of the calculation. 但是,由于精度问题,当您显示计算结果时,您可能还需要使用.toFixed(2) Using your example, 1.5 + 1.47 may result in 2.9699999999999998 — using .toFixed(2) will correct this imprecision to 2.97 . 使用您的示例, 1.5 + 1.47可能会导致2.9699999999999998 - 使用.toFixed(2)会将此不精确度更正为2.97

var discountAmount = 0;
var ogCookie = < %= strJsonCookie % >
for (var i = 0; i < ogCookie.products.length; i++) {
    discountAmount += parseFloat(ogCookie.products[i].discount_amount);
}
// Output at 2 decimal places
alert(discountAmount.toFixed(2));

Note also that I also optimized your code slightly by removing an unnecessary call to parseFloat and using the addition assignment operator ( += ). 另请注意,我还通过删除对parseFloat的不必要调用并使用添加赋值运算符( += )来略微优化代码。

使用'parsefloat()'来提取数字。

Use parseFloat, not parseInt. 使用parseFloat,而不是parseInt。 parseInt will turn everything into an integer. parseInt会将所有内容都变成整数。

Also, why are you using what I assume is php to output the same value to javascript several times? 另外,为什么你使用我认为是php的几次输出相同的值到javascript? Output it once and store it in a variable! 输出一次并将其存储在变量中! This will also let you put the javascript in a separate file and cache it/deliver it via CDN. 这也可以让你将javascript放在一个单独的文件中并通过CDN缓存它/传递它。

1.47 + 1.5 where both numbers are reals does not equal 1.97. 1.47 + 1.5这两个数字都是实数不等于1.97。 Perhaps that is your problem? 也许那是你的问题?

Otherwise, what is your question? 否则,你的问题是什么? What is the problem you are having with the above code? 您使用上述代码有什么问题? Could a jsFiddle demonstrate it? 一个jsFiddle可以证明吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM