javascript - 美元金额的上限
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4817296/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript - ceiling of a dollar amount
提问by bmarti44
So I am adding and subtracting floats in javascript, and I need to know how to always take the ceiling of any number that has more than 3 decimal places. For example:
所以我在 javascript 中添加和减去浮点数,我需要知道如何总是取任何超过 3 个小数位的数字的上限。例如:
3.19 = 3.19
3.19 = 3.19
3.191 = 3.20
3.191 = 3.20
3.00000001 = 3.01
3.00000001 = 3.01
回答by David Tang
num = Math.ceil(num * 100) / 100;
Though, due to the way floats are represented, you may not get a clean number that's to two decimal places. For display purposes, always do num.toFixed(2).
但是,由于浮点数的表示方式,您可能无法得到精确到小数点后两位的数字。出于显示目的,请始终执行num.toFixed(2).
回答by Amnon
Actually I don't think you want to represent dollar amounts as float, due to the same reason cited by Box9. For example, 0.1*3 != 0.3 in my browser. It's better to represent them as integers (e.g. cents).
实际上,由于 Box9 引用的相同原因,我认为您不想将美元金额表示为浮动金额。例如,0.1*3 != 0.3 在我的浏览器中。最好将它们表示为整数(例如美分)。

