How do you get rid of decimals in html?

I have the results of a division and I wish to discard the decimal portion of the resultant number.

How can I do this?

asked Oct 3, 2011 at 23:27

JacobTheDevJacobTheDev

16.4k24 gold badges88 silver badges153 bronze badges

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.

answered Oct 3, 2011 at 23:29

5

You can also use bitwise operators to truncate the decimal.

e.g.

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 

Chủ Đề