本文翻译自:How do you round to 1 decimal place in Javascript?
Can you round a number in javascript to 1 character after the decimal point (properly rounded)? 您可以将javascript中的数字四舍五入到小数点后的1个字符(正确舍入)吗?
I tried the *10, round, /10 but it leaves two decimals at the end of the int. 我尝试了* 10,舍入,/ 10,但是它在int末尾保留了两位小数。
#1楼
参考:https://stackoom.com/question/UoEn/如何在JavaScript中舍入到小数点后-位
#2楼
If you use Math.round(5.01)
you will get 5
instead of 5.0
. 如果使用Math.round(5.01)
您将获得5
而不是5.0
。
If you use toFixed
you run into rounding issues . 如果使用toFixed
则会遇到舍入 问题 。
If you want the best of both worlds combine the two: 如果您想两全其美,请将两者结合起来:
(Math.round(5.01 * 10) / 10).toFixed(1)
You might want to create a function for this: 您可能要为此创建一个函数:
function roundedToFixed(_float, _digits){
var rounded = Math.pow(10, _digits);
return (Math.round(_float * rounded) / rounded).toFixed(_digits);
}
#3楼
Try with this: 试试这个:
var original=28.453
// 1.- round "original" to two decimals
var result = Math.round (original * 100) / 100 //returns 28.45
// 2.- round "original" to 1 decimal
var result = Math.round (original * 10) / 10 //returns 28.5
// 3.- round 8.111111 to 3 decimals
var result = Math.round (8.111111 * 1000) / 1000 //returns 8.111
less complicated and easier to implement... 不太复杂且易于实现...
with this, you can create a function to do: 这样,您可以创建一个函数来执行以下操作:
function RoundAndFix (n, d) {
var m = Math.pow (10, d);
return Math.round (n * m) / m;
}
function RoundAndFix (n, d) { var m = Math.pow (10, d); return Math.round (n * m) / m; } console.log (RoundAndFix(8.111111, 3));
EDIT : see this How to round using ROUND HALF UP. 编辑 :请参阅此如何使用圆形半舍入。 Rounding mode that most of us were taught in grade school 我们大多数人在小学时教过的舍入模式
#4楼
x = number, n = decimal-places: x =数字,n =小数位:
function round(x, n) {
return Math.round(x * Math.pow(10, n)) / Math.pow(10, n)
}
#5楼
This seems to work reliably across anything I throw at it: 这似乎在我扔给它的任何东西上都能可靠地工作:
function round(val, multiplesOf) {
var s = 1 / multiplesOf;
var res = Math.ceil(val*s)/s;
res = res < val ? res + multiplesOf: res;
var afterZero = multiplesOf.toString().split(".")[1];
return parseFloat(res.toFixed(afterZero ? afterZero.length : 0));
}
It rounds up, so you may need to modify it according to use case. 它会四舍五入,因此您可能需要根据用例进行修改。 This should work: 这应该工作:
console.log(round(10.01, 1)); //outputs 11
console.log(round(10.01, 0.1)); //outputs 10.1
#6楼
If you care about proper rounding up then: 如果您关心适当的舍入,则:
function roundNumericStrings(str , numOfDecPlacesRequired){
var roundFactor = Math.pow(10, numOfDecPlacesRequired);
return (Math.round(parseFloat(str)*roundFactor)/roundFactor).toString(); }
Else if you don't then you already have a reply from previous posts 否则,如果您不这样做,那么您已经收到以前帖子的回复
str.slice(0, -1)