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

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


当前回答

我做了一个返回数字类型,也只在需要的时候放置小数(没有0填充)。

例子:

roundWithMaxPrecision(11.234, 2); //11.23
roundWithMaxPrecision(11.234, 1); //11.2
roundWithMaxPrecision(11.234, 4); //11.23
roundWithMaxPrecision(11.234, -1); //10

roundWithMaxPrecision(4.2, 2); //4.2
roundWithMaxPrecision(4.88, 1); //4.9

代码:

function roundWithMaxPrecision (n, precision) {
    const precisionWithPow10 = Math.pow(10, precision);
    return Math.round(n * precisionWithPow10) / precisionWithPow10;
}

其他回答

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

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

完成最佳答案:

var round = function ( number, precision )
{
    precision = precision || 0;
    return parseFloat( parseFloat( number ).toFixed( precision ) );
}

输入参数number可能"not"总是一个数字,在这种情况下。tofixed不存在。

const solds = 136780000000; 
const number = (solds >= 1000000000 && solds < 1000000000000) ? { divisor: 1000000000, postfix: "B" }: (solds >= 1000000 && solds < 1000000000) ? { divisor: 1000000, postfix: "M" }: (solds >= 1000 && solds < 1000000) ? { divisor: 1000, postfix: "K" }: { divisor: 1, postfix: null }; 
const floor = Math.floor(solds / number.divisor).toLocaleString(); 
const firstDecimalIndex = solds.toLocaleString().charAt(floor.length+1); 
const final =firstDecimalIndex.match("0")? floor + number.postfix: floor + "." + firstDecimalIndex + number.postfix; 
console.log(final);

136780000000 --> 136.7B

1367800 --> 1.3M

1342 --> 1.3K

Math.round( mul/count * 10 ) / 10

Math.round(Math.sqrt(sqD/y) * 10 ) / 10

谢谢

为什么不干脆

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

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