Programing

JavaScript 번호에서 소수 부분을 제거하려면 어떻게해야합니까?

lottogame 2020. 5. 15. 07:57
반응형

JavaScript 번호에서 소수 부분을 제거하려면 어떻게해야합니까?


나눗셈 결과가 있고 결과 숫자의 소수 부분을 버리고 싶습니다.

어떻게해야합니까?


당신은 사용할 수 있습니다 ...

... 소수점 제거 방법에 따라 다릅니다.

Math.trunc()아직 모든 플랫폼 (IE)에서 지원되는 것은 아니지만 그 동안 폴리 필쉽게 사용할 수 있습니다 .

우수한 플랫폼지지를 갖는 분수 부분을 절단하는 다른 방법은 비트 연산자 (예를 들어 |0)를 사용하는 것이다. 숫자에 비트 연산자를 사용하는 부작용은 피연산자를 부호있는 32 비트 정수로 취급하므로 분수 구성 요소가 제거된다는 것입니다. 이것은 또한 32 비트보다 큰 숫자를 맹 글링한다는 것을 명심하십시오.


부동 소수점 산술과 십진 반올림의 부정확성에 대해 이야기 할 수도 있습니다.

필요한 읽기-모든 컴퓨터 과학자가 부동 소수점 산술에 대해 알아야 할 사항 .


비트 연산자를 사용하여 소수를자를 수도 있습니다.

예 :

var x = 9 / 2;
console.log(x); // 4.5

x = ~~x;
console.log(x); // 4

x = -3.7
console.log(~~x) // -3
console.log(x | 0) // -3
console.log(x << 0) // -3

비트 단위 연산은 수학 함수보다 훨씬 효율적입니다. 비트가 아닌 비트 연산자는 무시할 정도로 비트 연산 x | 0x << 0비트 연산의 성능을 약간 능가합니다 .

// 952 milliseconds
for (var i = 0; i < 1000000; i++) {
    (i * 0.5) | 0;
}

// 1150 milliseconds
for (var i = 0; i < 1000000; i++) {
    (i * 0.5) << 0;
}

// 1284 milliseconds
for (var i = 0; i < 1000000; i++) {
    Math.trunc(i * 0.5);
}

// 939 milliseconds
for (var i = 0; i < 1000000; i++) {
    ~~(i * 0.5);
}

또한 비트 단위 연산자가 산술 연산보다 우선하므로 계산 결과를 괄호로 묶어야 원하는 결과를 얻을 수 있습니다.

x = -3.7

console.log(~~x * 2) // -6
console.log(x * 2 | 0) // -7
console.log(x * 2 << 0) // -7

console.log(~~(x * 2)) // -7
console.log(x * 2 | 0) // -7
console.log(x * 2 << 0) // -7

이중 비트 NOT 연산자에 대한 자세한 정보는 Double bitwise NOT (~~) 에서 찾을 수 있습니다.


당신은 또한 할 수 있습니다

parseInt(a/b)

u는 다음 코드를 사용하여 소수점 이하의 특정 자릿수 (여기서는 두 자리 숫자)를 표시 할 수도 있습니다

var num = (15.46974).toFixed(2)
console.log(num) // 15.47
console.log(typeof num) // string


사용하십시오 Math.round().

(Alex의 답변이 더 좋습니다. 나는 가정했습니다.)


Math.round()기능을 사용하십시오 .

Math.round(65.98) // will return 66 
Math.round(65.28) // will return 65

ES2015에서는 Math.trunc () 를 사용할 수 있습니다.

Math.trunc(2.3)                       // 2
Math.trunc(-2.3)                      // -2
Math.trunc(22222222222222222222222.3) // 2.2222222222222223e+22
Math.trunc("2.3")                     // 2
Math.trunc("two")                     // NaN
Math.trunc(NaN)                       // NaN

It's not supported in IE11 or below, but does work in Edge and every other modern browser.


Here is the compressive in detailed explanation with the help of above posts:

1. Math.trunc() : It is used to remove those digits which are followed by dot. It converts implicitly. But, not supported in IE.

Example:

Math.trunc(10.5) // 10

Math.trunc(-10.5) // -10

Other Alternative way: Use of bitwise not operator:

Example:

x= 5.5

~~x // 5

2. Math.floor() : It is used to give the minimum integer value posiible. It is supported in all browsers.

Example:

Math.floor(10.5) // 10

Math.floor( -10.5) // -11

3. Math.ceil() : It is used to give the highest integer value possible. It is supported in all browsers.

Example:

Math.ceil(10.5) // 11

Math.ceil(-10.5) // -10

4. Math.round() : It is rounded to the nearest integer. It is supported in all browsers.

Example:

Math.round(10.5) // 11

Math.round(-10.5)// -10

Math.round(10.49) // 10

Math.round(-10.51) // -11


If you don't care about rouding, just convert the number to a string, then remove everything after the period including the period. This works whether there is a decimal or not.

const sEpoch = ((+new Date()) / 1000).toString();
const formattedEpoch = sEpoch.split('.')[0];

toFixed will behave like round.

For a floor like behavior use %:

var num = 3.834234;
var floored_num = num - (num % 1); // floored_num will be 3

For an ES6 implementation, use something like the following:

const millisToMinutesAndSeconds = (millis) => {
  const minutes = Math.floor(millis / 60000);
  const seconds = ((millis % 60000) / 1000).toFixed(0);
  return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
}

This is for those who want to prevent users to enter decimal numbers

<input id="myInput" onkeyup="doSomething()" type="number" />

<script>
    function doSomething() {

        var intNum = $('#myInput').val();

        if (!Number.isInteger(intNum)) {
            intNum = Math.round(intNum);
        }

        console.log(intNum);
    }
</script>

참고URL : https://stackoverflow.com/questions/7641818/how-can-i-remove-the-decimal-part-from-javascript-number

반응형