Как округлить числа float в javascript?
мне надо, например 6.688689
to 6.7
, но он всегда показывает мне 7
.
мой метод:
Math.round(6.688689);
//or
Math.round(6.688689, 1);
//or
Math.round(6.688689, 2);
но результат всегда один и тот же 7
... Что я делаю не так?
14 ответов
вы можете использовать вспомогательную функцию из MDN пример. Чем вы будете иметь больше гибкости:
Math.round10(5.25, 0); // 5
Math.round10(5.25, -1); // 5.3
Math.round10(5.25, -2); // 5.25
Math.round10(5, 0); // 5
Math.round10(5, -1); // 5
Math.round10(5, -2); // 5
> +(6.688687).toPrecision(2)
6.7
A Number
объект в JavaScript имеет метод, который делает именно то, что вам нужно. этот метод Number.toPrecision([precision])
.
как с .toFixed(1)
он преобразует результат в строку, и его нужно преобразовать обратно в число. Сделано с помощью +
префикс здесь.
простой тест на моем ноутбуке:
number = 25.645234 typeof number
50000000 x number.toFixed(1) = 25.6 typeof string / 17527ms
50000000 x +(number.toFixed(1)) = 25.6 typeof number / 23764ms
50000000 x number.toPrecision(3) = 25.6 typeof string / 10100ms
50000000 x +(number.toPrecision(3)) = 25.6 typeof number / 18492ms
50000000 x Math.round(number*10)/10 = 25.6 typeof number / 58ms
string = 25.645234 typeof string
50000000 x Math.round(string*10)/10 = 25.6 typeof number / 7109ms
см. ниже
var original = 28.59;
var result=Math.round(original*10)/10
вернет вам возвращает 28.6
надеюсь, это то, что вы хотите..
если вы не только хотите использовать toFixed()
, но и ceil()
и floor()
на поплавке вы можете использовать следующую функцию:
function roundUsing(func, number, prec) {
var tempnumber = number * Math.pow(10, prec);
tempnumber = func(tempnumber);
return tempnumber / Math.pow(10, prec);
}
выдает:
> roundUsing(Math.floor, 0.99999999, 3)
0.999
> roundUsing(Math.ceil, 0.1111111, 3)
0.112
UPD:
другой возможный способ таков:
Number.prototype.roundUsing = function(func, prec){
var temp = this * Math.pow(10, prec)
temp = func(temp);
return temp / Math.pow(10, prec)
}
выдает:
> 6.688689.roundUsing(Math.ceil, 1)
6.7
> 6.688689.roundUsing(Math.round, 1)
6.7
> 6.688689.roundUsing(Math.floor, 1)
6.6
моя расширенная круглая функция:
function round(value, precision) {
if (Number.isInteger(precision)) {
var shift = Math.pow(10, precision);
return Math.round(value * shift) / shift;
} else {
return Math.round(value);
}
}
Пример:
round(123.688689) // 123
round(123.688689, 0) // 123
round(123.688689, 1) // 123.7
round(123.688689, 2) // 123.69
round(123.688689, -2) // 100
float(value,ndec);
function float(num,x){
this.num=num;
this.x=x;
var p=Math.pow(10,this.x);
return (Math.round((this.num).toFixed(this.x)*p))/p;
}
Я думаю, что эта функция может помочь.
function round(value, ndec){
var n = 10;
for(var i = 1; i < ndec; i++){
n *=10;
}
if(!ndec || ndec <= 0)
return Math.round(value);
else
return Math.round(value * n) / n;
}
round(2.245, 2) //2.25
round(2.245, 0) //2
Я думаю, что ниже функция может помочь
function roundOff(value,round) {
return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}
использование : roundOff(600.23458,2);
вернутся 600.23
Если вы находитесь в узле.контекст js, вы можете попробовать mathjs
const math = require('mathjs')
math.round(3.1415926, 2)
// result: 3.14
Если вы используете Browserify сегодня, вам придется попробовать: roundTo очень полезный NPM lib