I have the results of a division and I wish to discard the decimal portion of the resultant number.
How can I do this?
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.