简体   繁体   English

如何在JavaScript中舍入数字?

[英]How do I round a number in JavaScript?

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 . 问题是值有时可能是浮点数(具有不同的精度),整数,甚至是2.20011E+17的形式。 What I want to output are pure integers. 我想输出的是纯整数。 I don't know a lot of JavaScript, though. 不过,我不太了解很多JavaScript。 How would I go about writing a method that takes these sometimes-floats and makes them integers? 我将如何编写一个有时采用浮点数并使它们成为整数的方法?

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;
        }

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

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: Math对象为我们提供了三种可以使用的舍入方法:

The Math.round() is most commonly used, it returns the value rounded to the nearest integer. Math.round()是最常用的,它返回舍入到最接近的整数的值。 Then there is the Math.floor() wich returns the largest integer less than or equal to a number. 然后是Math.floor(),它返回小于或等于数字的最大整数。 Lastly we have the Math.ceil() function that returns the smallest integer greater than or equal to a number. 最后,我们有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. Ps。:Math.round()方法中没有第二个参数 The toFixed() is not IE specific , its within the ECMAScript specification aswell toFixed() 不是IE特定的 ,它 ECMAScript规范中也是如此

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

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 所有主流浏览器都支持这两种方法

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()将变量强制转换为某种类型,在本例中为整数和浮点。

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. 只有在某些情况下,当数字的小数部分的长度很长时才会出错。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM