你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?

我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。


当前回答

为什么不干脆

let myNumber = 213.27321;
+myNumber.toFixed(1); // => 213.3

toFixed: 返回使用定点表示法表示给定数字的字符串。 一元加号(+):一元加号运算符位于其操作数之前,求值为其操作数,但尝试将其转换为数字(如果它还不是数字)。

其他回答

数学。Round (num * 10) / 10工作,这里是一个例子…

var number = 12.3456789
var rounded = Math.round(number * 10) / 10
// rounded is 12.3

如果你想让它有一个小数点,即使它是0,然后加…

var fixed = rounded.toFixed(1)
// fixed is always to 1 d.p.
// NOTE: .toFixed() returns a string!

// To convert back to number format
parseFloat(number.toFixed(2))
// 12.34
// but that will not retain any trailing zeros

// So, just make sure it is the last step before output,
// and use a number format during calculations!

编辑:添加圆与精度功能…

使用这个原理,作为参考,这里有一个方便的小圆函数,它需要精度…

function round(value, precision) {
    var multiplier = Math.pow(10, precision || 0);
    return Math.round(value * multiplier) / multiplier;
}

... 使用……

round(12345.6789, 2) // 12345.68
round(12345.6789, 1) // 12345.7

... 默认舍入到最接近的整数(精度为0)…

round(12345.6789) // 12346

... 可以四舍五入到最接近的10或100等…

round(12345.6789, -1) // 12350
round(12345.6789, -2) // 12300

... 正确处理负数……

round(-123.45, 1) // -123.4
round(123.45, 1) // 123.5

... 并且可以与toFixed结合使用,以一致的格式作为字符串…

round(456.7, 2).toFixed(2) // "456.70"
var number = 123.456;

console.log(number.toFixed(1)); // should round to 123.5

我找到了一个避免精度问题的方法:

function badRound (num, precision) {
    const x = 10 ** precision;
    return Math.round(num * x) / x
}
// badRound(1.005, 2) --> 1

function round (num, precision) {
    const x = 10 ** (precision + 1);
    const y = 10 ** precision;
    return Math.round(Math.round(num * x) / 10) / y
}
// round(1.005, 2) --> 1.01

Angular的小过滤器,如果有人想要的话:

angular.module('filters').filter('decimalPlace', function() {
    return function(num, precision) {
        var multiplier = Math.pow(10, precision || 0);
        return Math.round(num * multiplier) / multiplier;
    };
});

使用if via:

{{model.value| decimalPlace}}
{{model.value| decimalPlace:1}}
{{model.value| decimalPlace:2}}

:)

你可以简单地做以下几点:

let n = 1.25
let result = Number(n).toFixed(1)
// output string: 1.3