如何在JavaScript中四舍五入数字?

时间:2021-10-03 09:15:59

While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of

在做一个项目的时候,我遇到了一个以前的员工创建的js脚本,它基本上以以下的形式创建一个报告

Name : Value
Name2 : Value2

etc.

等。

The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?

peoblem的意思是值有时可以是浮点数(具有不同的精度)、整数,甚至可以是形式为2.20011E+17。我想输出的是纯整数。我不太懂JavaScript。我该如何编写一个方法来获取这些时间-浮点数并使它们为整数?

8 个解决方案

#1


50  

You hav to convert your input into a number and then round them:

你必须把你的输入转换成一个数字,然后把它们四舍五入:

function toInteger(number){ 
  return Math.round(  // round to nearest integer
    Number(number)    // type cast your input
  ); 
};

Or as a one liner:

或者作为一句俏皮话:

function toInt(n){ return Math.round(Number(n)); };

Testing with different values:

测试不同的价值观:

toInteger(2.5);           // 3
toInteger(1000);          // 1000
toInteger("12345.12345"); // 12345
toInteger("2.20011E+17"); // 220011000000000000

#2


103  

If you need to round to a certain number of digits use the following function

如果您需要四舍五入到某个数字,请使用以下函数

function roundNumber(number, digits) {
            var multiple = Math.pow(10, digits);
            var rndedNum = Math.round(number * multiple) / multiple;
            return rndedNum;
        }

#3


29  

According to the ECMAScript specification, numbers in JavaScript are represented only by the double-precision 64-bit format IEEE 754. Hence there is not really an integer type in JavaScript.

根据ECMAScript规范,JavaScript中的数字仅由双精度64位格式的IEEE 754表示。因此JavaScript中并没有真正的整数类型。

Regarding the rounding of these numbers, there are a number of ways you can achieve this. The Math object gives us three rounding methods wich we can use:

关于这些数字的舍入,有很多方法可以实现这一点。数学对象给出了我们可以使用的三种四舍五入方法:

The Math.round() is most commonly used, it returns the value rounded to the nearest integer. Then there is the Math.floor() wich returns the largest integer less than or equal to a number. Lastly we have the Math.ceil() function that returns the smallest integer greater than or equal to a number.

Math.round()是最常用的,它返回四舍五入到最近整数的值。然后是Math.floor() wich返回小于或等于一个数字的最大整数。最后,我们有Math.ceil()函数,它返回大于或等于一个数字的最小整数。

There is also the toFixed() that returns a string representing the number using fixed-point notation.

还有一个toFixed(),它返回一个使用定点表示法表示数字的字符串。

Ps.: There is no 2nd argument in the Math.round() method. The toFixed() is not IE specific, its within the ECMAScript specification aswell

在Math.round()方法中没有第二个参数。toFixed()不是IE特定的,它也在ECMAScript规范中

#4


25  

Here is a way to be able to use Math.round() with a second argument (number of decimals for rounding):

这里有一种方法可以使用第二个参数Math.round(小数位数):

// 'improve' Math.round() to support a second argument
var _round = Math.round;
Math.round = function(number, decimals /* optional, default 0 */)
{
  if (arguments.length == 1)
    return _round(number);

  var multiplier = Math.pow(10, decimals);
  return _round(number * multiplier) / multiplier;
}

// examples
Math.round('123.4567', 2); // => 123.46
Math.round('123.4567');    // => 123

#5


20  

You can also use toFixed(x) or toPrecision(x) where x is the number of digits.

还可以使用toFixed(x)或toPrecision(x),其中x是位数。

Both these methods are supported in all major browsers

所有主要浏览器都支持这两种方法

#6


15  

You can use Math.round() for rounding numbers to the nearest integer.

可以使用Math.round()将数字四舍五入到最近的整数。

Math.round(532.24) => 532

Also, you can use parseInt() and parseFloat() to cast a variable to a certain type, in this case integer and floating point.

此外,您还可以使用parseInt()和parseFloat()将变量转换为特定类型,在这种情况下是整数和浮点数。

#7


0  

A very good approximation for rounding:

一个非常好的四舍五入近似:

function Rounding (number, precision){

var newNumber;
var sNumber = number.toString();

var increase = precision + sNumber.length - sNumber.indexOf('.') + 1;

if (number < 0)
  newNumber = (number -  5 * Math.pow(10,-increase));
else
  newNumber = (number +  5 * Math.pow(10,-increase));

var multiple = Math.pow(10,precision);

return Math.round(newNumber * multiple)/multiple;
}

Only in some cases when the length of the decimal part of the number is very long will it be incorrect.

只有在某些情况下,当小数部分的长度很长时,它是不正确的。

#8


-1  

Math.floor(19.5) = 19 should also work.

Math.floor(19.5) = 19也应该有效。

#1


50  

You hav to convert your input into a number and then round them:

你必须把你的输入转换成一个数字,然后把它们四舍五入:

function toInteger(number){ 
  return Math.round(  // round to nearest integer
    Number(number)    // type cast your input
  ); 
};

Or as a one liner:

或者作为一句俏皮话:

function toInt(n){ return Math.round(Number(n)); };

Testing with different values:

测试不同的价值观:

toInteger(2.5);           // 3
toInteger(1000);          // 1000
toInteger("12345.12345"); // 12345
toInteger("2.20011E+17"); // 220011000000000000

#2


103  

If you need to round to a certain number of digits use the following function

如果您需要四舍五入到某个数字,请使用以下函数

function roundNumber(number, digits) {
            var multiple = Math.pow(10, digits);
            var rndedNum = Math.round(number * multiple) / multiple;
            return rndedNum;
        }

#3


29  

According to the ECMAScript specification, numbers in JavaScript are represented only by the double-precision 64-bit format IEEE 754. Hence there is not really an integer type in JavaScript.

根据ECMAScript规范,JavaScript中的数字仅由双精度64位格式的IEEE 754表示。因此JavaScript中并没有真正的整数类型。

Regarding the rounding of these numbers, there are a number of ways you can achieve this. The Math object gives us three rounding methods wich we can use:

关于这些数字的舍入,有很多方法可以实现这一点。数学对象给出了我们可以使用的三种四舍五入方法:

The Math.round() is most commonly used, it returns the value rounded to the nearest integer. Then there is the Math.floor() wich returns the largest integer less than or equal to a number. Lastly we have the Math.ceil() function that returns the smallest integer greater than or equal to a number.

Math.round()是最常用的,它返回四舍五入到最近整数的值。然后是Math.floor() wich返回小于或等于一个数字的最大整数。最后,我们有Math.ceil()函数,它返回大于或等于一个数字的最小整数。

There is also the toFixed() that returns a string representing the number using fixed-point notation.

还有一个toFixed(),它返回一个使用定点表示法表示数字的字符串。

Ps.: There is no 2nd argument in the Math.round() method. The toFixed() is not IE specific, its within the ECMAScript specification aswell

在Math.round()方法中没有第二个参数。toFixed()不是IE特定的,它也在ECMAScript规范中

#4


25  

Here is a way to be able to use Math.round() with a second argument (number of decimals for rounding):

这里有一种方法可以使用第二个参数Math.round(小数位数):

// 'improve' Math.round() to support a second argument
var _round = Math.round;
Math.round = function(number, decimals /* optional, default 0 */)
{
  if (arguments.length == 1)
    return _round(number);

  var multiplier = Math.pow(10, decimals);
  return _round(number * multiplier) / multiplier;
}

// examples
Math.round('123.4567', 2); // => 123.46
Math.round('123.4567');    // => 123

#5


20  

You can also use toFixed(x) or toPrecision(x) where x is the number of digits.

还可以使用toFixed(x)或toPrecision(x),其中x是位数。

Both these methods are supported in all major browsers

所有主要浏览器都支持这两种方法

#6


15  

You can use Math.round() for rounding numbers to the nearest integer.

可以使用Math.round()将数字四舍五入到最近的整数。

Math.round(532.24) => 532

Also, you can use parseInt() and parseFloat() to cast a variable to a certain type, in this case integer and floating point.

此外,您还可以使用parseInt()和parseFloat()将变量转换为特定类型,在这种情况下是整数和浮点数。

#7


0  

A very good approximation for rounding:

一个非常好的四舍五入近似:

function Rounding (number, precision){

var newNumber;
var sNumber = number.toString();

var increase = precision + sNumber.length - sNumber.indexOf('.') + 1;

if (number < 0)
  newNumber = (number -  5 * Math.pow(10,-increase));
else
  newNumber = (number +  5 * Math.pow(10,-increase));

var multiple = Math.pow(10,precision);

return Math.round(newNumber * multiple)/multiple;
}

Only in some cases when the length of the decimal part of the number is very long will it be incorrect.

只有在某些情况下,当小数部分的长度很长时,它是不正确的。

#8


-1  

Math.floor(19.5) = 19 should also work.

Math.floor(19.5) = 19也应该有效。