你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
当前回答
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
其他回答
你可以简单地做以下几点:
let n = 1.25
let result = Number(n).toFixed(1)
// output string: 1.3
我做了一个返回数字类型,也只在需要的时候放置小数(没有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;
}
如果你使用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);
}
数学。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 value = Math.round(234.567*100)/100
234.56英镑可以吗
类似的
var value = Math.round(234.567*10)/10
会给出234.5
通过这种方式,您可以使用一个变量来代替前面使用的常量。