0

Possible Duplicate:
Truncate Decimal number not Round Off in jquery

I have values like 5.3777777, 4.6666666 on my Y variable.

How can I truncate it so it shows 5.3 or 5.6 instead with JavaScript?

Thanks in advance!

Community
  • 1
  • 1
Obsivus
  • 8,231
  • 13
  • 52
  • 97
  • 2
    This is a duplicate. Please try a few searches such as "javascript truncate number" (-1). –  May 22 '12 at 06:57

1 Answers1

6

The standard way to do this in any language is to multiple the value by the inverse of the precision required, truncate, and then divide again:

var truncated = Math.floor(val * 10) / 10;

If you want strict rounding rather than truncation then Javascript also has Number.toFixed() built-in which does this for you.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • `toFixed()` rounds the number, it doesn't truncate it. – JJJ May 22 '12 at 06:57
  • @Juhana text updated, thanks... – Alnitak May 22 '12 at 06:58
  • What if `val` is negative? (OK, probably negatives make a good "exercise for the reader"...) – nnnnnn May 22 '12 at 07:05
  • As nnnnnn says, this might produce unexpected results when the numbers are negative (it depends on what your expectations are). To handle the negative case check the question this is a duplicate of: http://stackoverflow.com/questions/4912788/truncate-not-round-off-decimal-numbers-in-javascript – Nick Knowlson Mar 02 '13 at 19:05