Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding the whole number portion of a number

Tags:

javascript

People also ask

What is the whole part of a number?

Any part or part of a whole one is known as a fraction.

How do you calculate whole numbers?

You would have to count one thousand whole numbers starting from zero and ending with one thousand, just like you would count ten whole numbers to count from zero to ten. A whole number is any number that is not a fraction or decimal. For example: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 are the whole numbers from zero to ten.

How do you find 1/4 of a whole number?

1 / 4 = 0.25 If you insist on converting 1/4 to a whole number, the best we can do is round the decimal number up or down to the nearest whole number. 1/4 rounded up to the nearest whole number is 1 and 1/4 rounded down to the nearest whole number is 0.


Using Math.floor:

Math.floor(number)

You can also use newNumber = parseInt(number, 10);


Bitwise operators - the shortest syntax for positive numbers having integral part of number <= 2^31-1

~~1.2 // 1
~~1.5 // 1
~~1.9 // 1

1.2>>0 // 1
1.5>>0 // 1
1.9>>0 // 1

1.2|0 // 1
1.5|0 // 1
1.9|0 // 1

With values exceeding 2^31-1 will return incorrect results.


With ES6, there is Math.trunc(), this function returns the integer part of a number by removing any fractional digits.

This differs from the Math.floor() while handling the negative numbers.

console.log(Math.trunc(3.14)); // 3

console.log(Math.trunc(-3.14)); // -3
console.log(Math.floor(-3.14)); // Here floor gives -4.

So essentially you can get rid of writing this longer expression

number > 0 ? Math.floor(number) : Math.ceil(number)

for negative numbers you can just use Math.abs(num) and it will knock off the - sign from the start