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

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


当前回答

为什么不干脆

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

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

其他回答

数学。整数(num * 10) / 10无效。

例如,1455581777.8-145558160.4会得到1310023617.3999999。

所以只使用num。tofixed (1)

var num = 34.7654;

num = Math.round(num * 10) / 10;

console.log(num); // Logs: 34.8
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

Lodash有一个循环方法:

_.round(4.006);
// => 4

_.round(4.006, 2);
// => 4.01

_.round(4060, -2);
// => 4100

文档。

源。

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

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

谢谢