I have the results of a division and I wish to discard the decimal portion of the resultant number.
How can I do this?
Step 1: Write down the decimal divided by 1. Step 2: Multiply both top and bottom by 10 for every number after the decimal point. (For example, if there are two numbers after the decimal point, then use 100, if there are three then use 1000, etc.) Step 3: Simplify (or reduce) the Rational number.
In JavaScript, trunc() is a function that is used to return the integer portion of a number. It truncates the number and removes all fractional digits. Because the trunc() function is a static function of the Math object, it must be invoked through the placeholder object called Math.
You could use...
Math.trunc()
(truncate fractional part, also see below)Math.floor()
(round down)Math.ceil()
(round up) Math.round()
(round to nearest integer)...dependent on how you wanted to remove the decimal.
Math.trunc()
isn't supported on all platforms yet (namely IE), but you could easily use a polyfill in the meantime.
Another method of truncating the fractional portion with excellent platform support is by using a bitwise operator (.e.g |0
). The side-effect of using a bitwise operator on a number is it will treat its operand as a signed 32bit integer, therefore removing the fractional component. Keep in mind this will also mangle numbers larger than 32 bits.
You may also be talking about the inaccuracy of decimal rounding with floating point arithmetic.
Required Reading - What Every Computer Scientist Should Know About Floating-Point Arithmetic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With