在 JavaScript 中四舍五入到最接近的小数点的百分之一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14968615/
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
Rounding to the nearest hundredth of a decimal in JavaScript
提问by Spencer Carpenter
I'm doing simple math in JavaScript using variables to represent the numbers. Here is an example of my code:
我正在用 JavaScript 做简单的数学运算,使用变量来表示数字。这是我的代码示例:
var ones = 0;
var fives = 0;
function results (){
_fives = (fives * 5);
var res = (_fives + ones);
document.innerHTML = res;
}
This isn't the full code but basically I'm having the user enter the amount of bills and coins from 1 cent coins up to $100 bills. The code multiplies the amount of bills to the amount the bill is worth. This is no problem works just fine... For some reason on some of my results it shows a decimal like 1.899999999997 not sure how this is happening.
这不是完整的代码,但基本上我让用户输入钞票和硬币的数量,从 1 美分硬币到 100 美元的钞票。该代码将账单金额乘以账单价值。这没问题,工作正常......出于某种原因,我的一些结果显示了像 1.899999999997 这样的小数,不知道这是怎么发生的。
Is there a way to change this so it round to the nearest hundredth of a decimal?
有没有办法改变它,使其四舍五入到最接近的小数点百分之一?
For example instead of it showing 1.89999999997 it would just show 1.90 in reality this isn't a big issue. This is a personal thing that I can just round it myself however it would be nice to learn how to do this for future reference.
例如,它不会显示 1.89999999997,它实际上只会显示 1.90,这不是什么大问题。这是个人的事情,我可以自己解决它,但是学习如何做到这一点以供将来参考会很好。
回答by Rodaine
UPDATE: MDN actually has a great example of decimal rounding that avoids floating point inaccuracies. Their method can be modified to always round up, based on the OP.
更新: MDN 实际上有一个很好的小数舍入示例,可以避免浮点不准确。他们的方法可以修改为总是向上取整,基于 OP。
ORIGINAL (SOMEWHAT INCORRECT) ANSWER
原始(有些不正确)答案
//to round to n decimal places
function round(num, places) {
var multiplier = Math.pow(10, places);
return Math.round(num * multiplier) / multiplier;
}
EDIT: I didn't read the question completely. Since we're talking currency, we probably want to round it up:
编辑:我没有完全阅读问题。由于我们在谈论货币,因此我们可能希望将其四舍五入:
//to round up to two decimal places
function money_round(num) {
return Math.ceil(num * 100) / 100;
}
回答by Jordan
Actually this method does NOT work in all cases. I'm doing something similar to round a measured value to a certain number of digits.
实际上,这种方法并不适用于所有情况。我正在做一些类似于将测量值四舍五入到一定数量的数字的事情。
In my case I have a a mean and standard deviation of a measurement, something like 0.20812345967 +/- 0.0031647859. Now obviously the extra significant digits are meaningless, so I'd like to write it as 0.208 +/- 0.003. When I do the floating point math, I get 0.20800000000000002 +/- 0.003
在我的例子中,我有一个测量的平均值和标准偏差,比如 0.20812345967 +/- 0.0031647859。现在显然额外的有效数字是没有意义的,所以我想把它写成 0.208 +/- 0.003。当我做浮点数学时,我得到 0.20800000000000002 +/- 0.003
Usually this rounds correctly, but because base ten decimal numbers sometimes can't be exactly stored in binary, you get crap like this.
通常这四舍五入是正确的,但是因为以十进制为基数的数字有时不能完全存储为二进制,所以你会得到这样的废话。
Instead, I'm going to look for a string format solution
相反,我要寻找一个字符串格式的解决方案
回答by brian-welch
I know that this is likely a day late and a dollar short, but I was also looking for something like this, and this question led me to look into the Math.round functionality
我知道这可能晚了一天,空了 1 美元,但我也在寻找这样的东西,这个问题让我研究了 Math.round 功能
I come up with this which successfully rounds a given value to the nearest 5th, 100th. So 0.07 becomes 0.05. 23.45 becomes 23.45. 1006.32 becomes 1006.30.
我想出了这个,它成功地将给定的值四舍五入到最接近的第 5 个、第 100 个。所以 0.07 变成了 0.05。23.45 变成 23.45。1006.32 变为 1006.30。
<script>
function rounder() {
var exampleInput = $("#inputId").val();
$("#output").html(((Math.round(((Math.round(exampleInput*100)/5)*5)/5)*5)/100).toFixed(2));
}
</script>
Being a novice, I am certain that there is a way to make this code more efficient.
作为新手,我确信有一种方法可以使此代码更高效。
回答by alexey28
This is known problem of JavaScript when you doing something like:
当您执行以下操作时,这是 JavaScript 的已知问题:
0.1 + 0.5 = 0.600000000001 or 0.599999999998
The solution for this problem is to use one of JavasSript library with fixed precision and rounding modes. You can try big-numbers. Here is code example:
此问题的解决方案是使用具有固定精度和舍入模式的 JavasSript 库之一。你可以试试big-numbers。这是代码示例:
// Initialization
var bn = new BigNumbers({
precision: 20, // fixed precision 20 digits after decimal separator
roundingMode: BigNumbers.RoundingMode.HALF_UP // rounding mode is Half Up
});
var number1 = bn.of('15');
var number2 = bn.of('12');
var divideResult = number1.divide(number2); // result "1.25"
var multiplyResult = divideResult.multiply(1/2); // result "0.625"
var roundingToTwoDecimalResult = multiplyResult.toPrecision(2); // result "0.63"
The JavaScript tutorialfor the same
回答by Nja
Rounding up tool for large decimals. Can be adjust to handle different decimals sizes by assigning 'decimal' a different value.
大小数的四舍五入工具。可以通过为“小数”分配不同的值来调整以处理不同的小数大小。
const roundToWholeNumber = (num, decimal = 100000) => {
const _roundingHelper = (val, decimalPlace) => {
return Math.round(val * decimalPlace) / decimalPlace;
}
while(decimal > 1){
num = _roundingHelper(num, decimal)
decimal = decimal / 10
}
return Math.round(num)
}
roundToWholeNumber(5.44444555)
回答by Thomas
I've actually been dealing with this as I've been working to implement a solution for rounding for a vectors project I am working on. I'm actually surprised this older (2011) javascripter.netresource hasn't made it, particularly as it is using Math.round( // ...mentioned previously.
我实际上一直在处理这个问题,因为我一直在努力为我正在处理的矢量项目实施舍入解决方案。我实际上很惊讶这个较旧的(2011 年)javascripter.net资源没有成功,特别是因为它正在使用Math.round( // ...前面提到的。
I've added a bit to it, also make use of .toFixed()(though this will lop off any trailing zeroes, which I am not too worried about, at this stage, personally):
我已经添加了一点,也使用.toFixed()(虽然这会删除任何尾随零,我不太担心,在这个阶段,个人):
const round = (number, places) => {
let rounder = '1';
for (let i = 0; i < places; i++) {
rounder += '0';
}
return (Math.round(number * rounder) / rounder).toFixed(places);
};
I'm sure there is some issue with the above in terms of efficiency or redundancy; but my point is that Math.round()still does what you need it to. Might need to throw a conversion in the above, after the iteration.
我确定上述内容在效率或冗余方面存在一些问题;但我的观点是,它Math.round()仍然可以满足您的需求。在迭代之后,可能需要在上面抛出一个转换。
It's also a heck of a lot easier to read than some of the other proposed solutions.
与其他一些建议的解决方案相比,它也更容易阅读。
回答by calcazar
This is what I personally decided to use in one of the apps I'm working on!
这是我个人决定在我正在开发的应用程序之一中使用的!
const roundToHundredth = (value) => {
return Number(value.toFixed(2));
};
console.log(roundToHundredth(1.98723232))
console.log(roundToHundredth(3.14159265359))
console.log(roundToHundredth(2.67528))

