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

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


当前回答

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

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

谢谢

其他回答

var number = 123.456;

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

Lodash有一个循环方法:

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

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

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

文档。

源。

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

如果你的方法不起作用,请发布你的代码。

然而,你可以完成舍入任务如下:

var value = Math.round(234.567*100)/100

234.56英镑可以吗

类似的

 var value = Math.round(234.567*10)/10

会给出234.5

通过这种方式,您可以使用一个变量来代替前面使用的常量。

如果你使用Math.round(5.01),你将得到5而不是5.0。

如果你使用固定你会遇到舍入问题。

如果你想两全其美,那就把两者结合起来:

(Math.round(5.01 * 10) / 10).toFixed(1)

你可能想为此创建一个函数:

function roundedToFixed(input, digits){
  var rounder = Math.pow(10, digits);
  return (Math.round(input * rounder) / rounder).toFixed(digits);
}