你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
当前回答
我投票给toFixed(),但是,为了记录,这里有另一种使用位移位将数字转换为int的方法。因此,它总是趋近于零(正数向下,负数向上)。
var rounded = ((num * 10) << 0) * 0.1;
但是,嘿,因为没有函数调用,它非常快。:)
这里有一个使用字符串匹配:
var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');
我不建议使用字符串变体,只是说。
其他回答
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}}
:)
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
function rnd(v,n=2) {
return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(10,n)
}
这个很好地抓住了极端情况
var num = 34.7654;
num = Math.round(num * 10) / 10;
console.log(num); // Logs: 34.8
Math.round( mul/count * 10 ) / 10
Math.round(Math.sqrt(sqD/y) * 10 ) / 10
谢谢