Uncategorized

JavaScript round float to n decimal points

The best you can do with built in JavaScript functions is to round a number to the nearest integer using the method Math.round(x), so to round a float to n decimal points we need to come up with our own function.

The function round_float() rounds a floating point number x to n decimals, if you ommit the parameter n, the function will have the same behaviour as the round() method, here is the round_float function definition:

With prototyping

Dmitry suggested a better approach using prototyping:

3 Comments

3 Comments

  1. Dmitry

    August 16, 2010 at 3:18 am

    It would be better to use prototyping here. Newer browsers support toFixed() function. Older don’t.
    So here’s the way to do it:

  2. Chat

    April 6, 2011 at 4:24 pm

    make it simpler

    • Nabil

      April 6, 2011 at 5:20 pm

      This is very clean, if val is not a number the function will return NaN (Not a Number)

      Thanks Chat!

Leave a Reply

Your email address will not be published. Required fields are marked *

To Top