用JavaScript处理价格和取整 [英] Dealing with prices and rounding in Javascript

查看:46
本文介绍了用JavaScript处理价格和取整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,众所周知, 0.1 + 0.2 等于 0.30000000000000004

So, as we all know, 0.1 + 0.2 is equivalent to 0.30000000000000004.

我有一个可以在卖点用来收钱的应用程序,我不想处理浮点运算的噩梦。我所看到的,我的选择是

I've got an application which will be used at a point of sell to collect money, and I don't want to deal with the nightmare of floating point arithmetic. My options, as I see them, are

a),使用整数并将价格作为美分/便士,在那儿做数学,然后然后除以100得到美元/磅的成本

a) using integers and dealing with prices as Cents/Pence, doing the math there, and then dividing by 100 to get the cost in Dollars/Pounds

b),使用小数库对数字进行精确的数学计算

b) using a Decimal library to do accurate math on the numbers

我正在使用react.js和webpack。有生产经验的人有什么建议吗?我倾向于选项a。

I'm using react.js and webpack. Anybody with production experience have any advice? I'm leaning toward option a.

推荐答案

执行所有货币操作(以及任何具有固定的小数位数)作为整数运算,然后将该值转换为小数以进行显示。仅在精度至关重要且小数位数随数字而变化的情况下,才使用十进制库。

It is an established convention to do all currency operations (and any operation that has a fixed number of decimal places for that matter) as integer operations and convert that value to decimal for display. Use a decimal library only if accuracy is vital and the number of decimal places varies from number to number.

这篇关于用JavaScript处理价格和取整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆