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.7A
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.112UPD:
другой возможный путь это:
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
Comments