Program Tip

JavaScript에서 float 숫자를 정수로 어떻게 변환합니까?

programtip 2020. 9. 27. 13:48
반응형

JavaScript에서 float 숫자를 정수로 어떻게 변환합니까?


JavaScript에서 부동 소수점을 정수로 변환하고 싶습니다. 사실, 표준 변환 (자르기 및 반올림)을 모두 수행하는 방법을 알고 싶습니다. 그리고 효율적으로 문자열로 변환하고 구문 분석하지 않습니다.


var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue ); 
var intvalue = Math.round( floatvalue );

// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );

수학 개체 참조


// value=x        //  x=5          5<x<5.5      5.5<=x<6  

Math.floor(value) //  5            5            5
Math.ceil(value)  //  5            6            6
Math.round(value) //  5            5            6
Math.trunc(value) //  5            5            5
parseInt(value)   //  5            5            5
~~value           //  5            5            5
value | 0         //  5            5            5
value >> 0        //  5            5            5
value >>> 0       //  5            5            5
value - value % 1 //  5            5            5
부정
// value=x        // x=-5         -5>x>=-5.5   -5.5>x>-6

Math.floor(value) // -5           -6           -6
Math.ceil(value)  // -5           -5           -5
Math.round(value) // -5           -5           -6
Math.trunc(value) // -5           -5           -5
parseInt(value)   // -5           -5           -5
value | 0         // -5           -5           -5
~~value           // -5           -5           -5
value >> 0        // -5           -5           -5
value >>> 0       // 4294967291   4294967291   4294967291
value - value % 1 // -5           -5           -5
양수-더 큰 숫자
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1

// value=x            x=900719925474099    x=900719925474099.4  x=900719925474099.5

Math.floor(value) //  900719925474099      900719925474099      900719925474099
Math.ceil(value)  //  900719925474099      900719925474100      900719925474100
Math.round(value) //  900719925474099      900719925474099      900719925474100
Math.trunc(value) //  900719925474099      900719925474099      900719925474099
parseInt(value)   //  900719925474099      900719925474099      900719925474099
value | 0         //  858993459            858993459            858993459
~~value           //  858993459            858993459            858993459
value >> 0        //  858993459            858993459            858993459
value >>> 0       //  858993459            858993459            858993459
value - value % 1 //  900719925474099      900719925474099      900719925474099
음수-더 큰 숫자
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1

// value = x      // x=-900719925474099   x=-900719925474099.5 x=-900719925474099.6

Math.floor(value) // -900719925474099     -900719925474100     -900719925474100
Math.ceil(value)  // -900719925474099     -900719925474099     -900719925474099
Math.round(value) // -900719925474099     -900719925474099     -900719925474100
Math.trunc(value) // -900719925474099     -900719925474099     -900719925474099
parseInt(value)   // -900719925474099     -900719925474099     -900719925474099
value | 0         // -858993459           -858993459           -858993459
~~value           // -858993459           -858993459           -858993459
value >> 0        // -858993459           -858993459           -858993459
value >>> 0       //  3435973837           3435973837           3435973837
value - value % 1 // -900719925474099     -900719925474099     -900719925474099

비트 OR 연산자

비트 또는 연산자를 사용하여 부동 소수점 숫자를자를 수 있으며 음수뿐만 아니라 양수에도 작동합니다.

function float2int (value) {
    return value | 0;
}

결과

float2int(3.1) == 3
float2int(-3.1) == -3
float2int(3.9) == 3
float2int(-3.9) == -3

성능 비교?

성능을 비교 하는 JSPerf 테스트만들었습니다 .

  • Math.floor(val)
  • val | 0 비트 OR
  • ~~val 비트 NOT
  • parseInt(val)

양수에서만 작동합니다. 이 경우 비트 연산과 Math.floor함수 를 사용하는 것이 안전 합니다.

But if you need your code to work with positives as well as negatives, then a bitwise operation is the fastest (OR being the preferred one). This other JSPerf test compares the same where it's pretty obvious that because of the additional sign checking Math is now the slowest of the four.

Note

As stated in comments, BITWISE operators operate on signed 32bit integers, therefore large numbers will be converted, example:

1234567890  | 0 => 1234567890
12345678901 | 0 => -539222987

Note: You cannot use Math.floor() as a replacement for truncate, because Math.floor(-3.1) = -4 and not -3 !!

A correct replacement for truncate would be:

function truncate(value)
{
    if (value < 0) {
        return Math.ceil(value);
    }

    return Math.floor(value);
}

A double bitwise not operator can be used to truncate floats. The other operations you mentioned are available through Math.floor, Math.ceil, and Math.round.

> ~~2.5
2
> ~~(-1.4)
-1

More details courtesy of James Padolsey.


For truncate:

var intvalue = Math.floor(value);

For round:

var intvalue = Math.round(value);

You can use the parseInt method for no rounding. Be careful with user input due to the 0x (hex) and 0 (octal) prefix options.

var intValue = parseInt(floatValue, 10);

Bit shift by 0 which is equivalent to division by 1

// >> or >>>
2.0 >> 0; // 2
2.0 >>> 0; // 2

In your case, when you want a string in the end (in order to insert commas), you can also just use the Number.toFixed() function, however, this will perform rounding.


There are many suggestions here. The bitwise OR seems to be the simplest by far. Here is another short solution which works with negative numbers as well using the modulo operator. It is probably easier to understand than the bitwise OR:

intval = floatval - floatval%1;

This method also works with high value numbers where neither '|0' nor '~~' nor '>>0' work correctly:

> n=4294967295;
> n|0
-1
> ~~n
-1
> n>>0
-1
> n-n%1
4294967295

One more possible way — use XOR operation:

console.log(12.3 ^ 0); // 12
console.log("12.3" ^ 0); // 12
console.log(1.2 + 1.3 ^ 0); // 2
console.log(1.2 + 1.3 * 2 ^ 0); // 3
console.log(-1.2 ^ 0); // -1
console.log(-1.2 + 1 ^ 0); // 0
console.log(-1.2 - 1.3 ^ 0); // -2

Priority of bitwise operations is less then priority of math operations, it's useful. Try on https://jsfiddle.net/au51uj3r/


To truncate:

// Math.trunc() is part of the ES6 spec
Math.trunc( 1.5 );  // returns 1
Math.trunc( -1.5 ); // returns -1
// Math.floor( -1.5 ) would return -2, which is probably not what you wanted

To round:

Math.round( 1.5 );  // 2
Math.round( 1.49 ); // 1
Math.round( -1.6 ); // -2
Math.round( -1.3 ); // -1

If look into native Math object in JavaScript, you get the whole bunch of functions to work on numbers and values, etc...

Basically what you want to do is quite simple and native in JavaScript...

Imagine you have the number below:

const myValue = 56.4534931;

and now if you want to round it down to the nearest number, just simply do:

const rounded = Math.floor(myValue);

and you get:

56

If you want to round it up to the nearest number, just do:

const roundedUp = Math.ceil(myValue);

and you get:

57

Also Math.round just round it to higher or lower number depends on which one is closer to the flot number.

Also you can use of ~~ behind the float number, that will convert a float to a whole number.

You can use it like ~~myValue...


I just want to point out that monetarily you want to round, and not trunc. Being off by a penny is much less likely, since 4.999452 * 100 rounded will give you 5, a more representative answer.

And on top of that, don't forget about banker's rounding, which is a way to counter the slightly positive bias that straight rounding gives -- your financial application may require it.

Gaussian/banker's rounding in JavaScript


If you are using angularjs then simple solution as follows In HTML Template Binding

{{val | number:0}}

it will convert val into integer

go through with this link docs.angularjs.org/api/ng/filter/number

참고URL : https://stackoverflow.com/questions/596467/how-do-i-convert-a-float-number-to-a-whole-number-in-javascript

반응형