JavaScript 数学,四舍五入到小数点后两位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15762768/
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 math, round to two decimal places
提问by Smudger
I have the following JavaScript syntax:
我有以下 JavaScript 语法:
var discount = Math.round(100 - (price / listprice) * 100);
This rounds up to the whole number. How can I return the result with two decimal places?
这四舍五入到整数。如何返回带有两位小数的结果?
回答by Rick Calder
NOTE - See Edit 4 if 3 digit precision is important
注意 - 如果 3 位精度很重要,请参阅编辑 4
var discount = (price / listprice).toFixed(2);
toFixed will round up or down for you depending on the values beyond 2 decimals.
toFixed 将根据超过 2 位小数的值为您四舍五入。
Example: http://jsfiddle.net/calder12/tv9HY/
示例:http: //jsfiddle.net/calder12/tv9HY/
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
文档:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Edit- As mentioned by others this converts the result to a string. To avoid this:
编辑- 正如其他人所提到的,这会将结果转换为字符串。为避免这种情况:
var discount = +((price / listprice).toFixed(2));
Edit 2- As also mentioned in the comments this function fails in some precision, in the case of 1.005 for example it will return 1.00 instead of 1.01. If accuracy to this degree is important I've found this answer: https://stackoverflow.com/a/32605063/1726511Which seems to work well with all the tests I've tried.
编辑 2- 正如评论中所提到的,该函数在某些精度上失败,例如在 1.005 的情况下,它将返回 1.00 而不是 1.01。如果这种程度的准确性很重要,我找到了这个答案:https: //stackoverflow.com/a/32605063/1726511这似乎适用于我尝试过的所有测试。
There is one minor modification required though, the function in the answer linked above returns whole numbers when it rounds to one, so for example 99.004 will return 99 instead of 99.00 which isn't ideal for displaying prices.
但是,需要进行一个小的修改,上面链接的答案中的函数在舍入为 1 时返回整数,因此例如 99.004 将返回 99 而不是 99.00,这不适合显示价格。
Edit 3- Seems having the toFixed on the actual return was STILL screwing up some numbers, this final edit appears to work. Geez so many reworks!
编辑 3- 似乎在实际返回时使用 toFixed 仍然搞砸了一些数字,这个最终编辑似乎有效。天啊这么多返工!
var discount = roundTo((price / listprice), 2);
function roundTo(n, digits) {
if (digits === undefined) {
digits = 0;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
var test =(Math.round(n) / multiplicator);
return +(test.toFixed(digits));
}
See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/
请参阅此处的小提琴示例:https: //jsfiddle.net/calder12/3Lbhfy5s/
Edit 4- You guys are killing me. Edit 3 fails on negative numbers, without digging into why it's just easier to deal with turning a negative number positive before doing the rounding, then turning it back before returning the result.
编辑 4- 你们杀了我。Edit 3 在负数上失败,没有深入研究为什么在进行舍入之前将负数变为正数,然后在返回结果之前将其转回更容易处理。
function roundTo(n, digits) {
var negative = false;
if (digits === undefined) {
digits = 0;
}
if( n < 0) {
negative = true;
n = n * -1;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
n = (Math.round(n) / multiplicator).toFixed(2);
if( negative ) {
n = (n * -1).toFixed(2);
}
return n;
}
回答by John Gietzen
If you use a unary plus to convert a string to a number as documented on MDN.
如果您使用一元加号将字符串转换为 MDN 上记录的数字。
For example:+discount.toFixed(2)
例如:+discount.toFixed(2)
回答by Arne H. Bitubekk
The functions Math.round() and .toFixed() is meant to round to the nearest integer. You'll get incorrect results when dealing with decimals and using the "multiply and divide" method for Math.round() or parameter for .toFixed(). For example, if you try to round 1.005 using Math.round(1.005 * 100) / 100 then you'll get the result of 1, and 1.00 using .toFixed(2) instead of getting the correct answer of 1.01.
函数 Math.round() 和 .toFixed() 旨在四舍五入到最接近的整数。在处理小数和使用 Math.round() 的“乘除”方法或 .toFixed() 的参数时,您会得到不正确的结果。例如,如果您尝试使用 Math.round(1.005 * 100) / 100 对 1.005 进行四舍五入,那么您将获得 1 的结果,使用 .toFixed(2) 获得 1.00 的结果,而不是获得 1.01 的正确答案。
You can use following to solve this issue:
您可以使用以下方法解决此问题:
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');
Add .toFixed(2) to get the two decimal places you wanted.
添加 .toFixed(2) 以获得您想要的两位小数。
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);
You could make a function that will handle the rounding for you:
您可以创建一个函数来为您处理舍入:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
Example: https://jsfiddle.net/k5tpq3pd/36/
示例:https: //jsfiddle.net/k5tpq3pd/36/
Alternativ
另类
You can add a round function to Number using prototype. I would not suggest adding .toFixed() here as it would return a string instead of number.
您可以使用原型向 Number 添加圆形函数。我不建议在这里添加 .toFixed() 因为它会返回一个字符串而不是数字。
Number.prototype.round = function(decimals) {
return Number((Math.round(this + "e" + decimals) + "e-" + decimals));
}
and use it like this:
并像这样使用它:
var numberToRound = 100 - (price / listprice) * 100;
numberToRound.round(2);
numberToRound.round(2).toFixed(2); //Converts it to string with two decimals
Example https://jsfiddle.net/k5tpq3pd/35/
示例 https://jsfiddle.net/k5tpq3pd/35/
Source: http://www.Hymanlmoore.com/notes/rounding-in-javascript/
资料来源:http: //www.Hymanlmoore.com/notes/rounding-in-javascript/
回答by Cattode
To get the result with two decimals, you can do like this :
要获得两位小数的结果,您可以这样做:
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.
要舍入的值乘以 100 保留前两位数字,然后除以 100 得到实际结果。
回答by Naga Srinu Kapusetti
The best and simple solution I found is
我发现的最好和最简单的解决方案是
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // 1.01
回答by Bryce
I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:
我认为我见过的最好的方法是乘以 10 的数字次幂,然后进行 Math.round,最后除以 10 的数字次幂。这是我在打字稿中使用的一个简单函数:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Or plain javascript:
或者普通的javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
回答by Harish
try using discount.toFixed(2);
尝试使用 discount.toFixed(2);
回答by HalfTitle
A small variation on the accepted answer.
toFixed(2)
returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:
接受的答案的一个小变化。
toFixed(2)
返回一个字符串,你总是得到两位小数。这些可能是零。如果您想抑制最终零,只需执行以下操作:
var discount = + ((price / listprice).toFixed(2));
Edited:
I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to
编辑:我刚刚发现似乎是 Firefox 35.0.1 中的一个错误,这意味着上面的内容可能会给 NaN 一些值。
我已将代码更改为
var discount = Math.round(price / listprice * 100) / 100;
This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
这给出了最多两位小数的数字。如果你想要三个,你可以乘以除以 1000,依此类推。
OP 总是需要两位小数,但如果 toFixed() 在 Firefox 中损坏,则需要先修复。
见https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
回答by Kamy D
Fastest Way- faster than toFixed():
最快的方式- 比 toFixed() 快:
TWO DECIMALS
两位小数
x = .123456
result = Math.round(x * 100) / 100 // result .12
THREE DECIMALS
三个小数
x = .123456
result = Math.round(x * 1000) / 1000 // result .123
回答by Chris Martin
function round(num,dec)
{
num = Math.round(num+'e'+dec)
return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)