By hoju


2010-02-08 11:19:56 8 Comments

in JavaScript, the typical way to round a number to N decimal places is something like:

function round_number(num, dec) {
    return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

However this approach will round to a maximum of N decimal places while I want to always round to N decimal places. For example "2.0" would be rounded to "2".

Any ideas?

9 comments

@KRISHNA TEJA 2017-09-08 19:24:19

I think below function can help

function roundOff(value,round) {
   return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}

usage : roundOff(600.23458,2); will return 600.23

@JohnnyBizzle 2016-08-16 09:02:50

PHP-Like rounding Method

The code below can be used to add your own version of Math.round to your own namespace which takes a precision parameter. Unlike Decimal rounding in the example above, this performs no conversion to and from strings, and the precision parameter works same way as PHP and Excel whereby a positive 1 would round to 1 decimal place and -1 would round to the tens.

var myNamespace = {};
myNamespace.round = function(number, precision) {
    var factor = Math.pow(10, precision);
    var tempNumber = number * factor;
    var roundedTempNumber = Math.round(tempNumber);
    return roundedTempNumber / factor;
};

myNamespace.round(1234.5678, 1); // 1234.6
myNamespace.round(1234.5678, -1); // 1230

from Mozilla Developer reference for Math.round()

@Juan Carrey 2014-04-16 07:57:31

If you do not really care about rounding, just added a toFixed(x) and then removing trailing 0es and the dot if necessary. It is not a fast solution.

function format(value, decimals) {
    if (value) {
        value = value.toFixed(decimals);            
    } else {
        value = "0";
    }
    if (value.indexOf(".") < 0) { value += "."; }
    var dotIdx = value.indexOf(".");
    while (value.length - dotIdx <= decimals) { value += "0"; } // add 0's

    return value;
}

@Elias Zamaria 2014-10-20 17:13:48

I tried format(1.2, 5) and got 1.2, while I expected 1.20000.

@Juan Carrey 2015-06-13 14:53:18

Sorry @EliasZamaria , didn't understand it at first. I have edited the post. Just note that it wil return "0.0000" when value is undefined.

@David 2011-08-18 07:08:50

I think that there is a more simple approach to all given here, and is the method Number.toFixed() already implemented in JavaScript.

simply write:

var myNumber = 2;

myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"

etc...

@David 2014-04-21 07:40:00

Where is mentioned, hoju? I reviewed other answers and I didn't find anyone reporting that toFixed function is buggy. Thanks

@Guffa 2015-06-05 15:55:38

@David: That's mentioned in a comment to the answer, for example.

@Jordan Arseno 2015-12-01 22:33:59

caution: toFixed() returns a string.

@epascarello 2015-12-16 05:16:22

@JordanArseno It has to be a string to be padded with zeros...

@Stephen Romero 2018-08-03 20:24:16

@JordanArseno this can be fixed using parseInt(myNumber.toFixed(intVar)); to return an integer value, or parseFloat(myNumber.toFixed(floatVar)); to return a float if user has decimal places.

@Elias Zamaria 2010-05-25 23:34:50

I found a way. This is Christoph's code with a fix:

function toFixed(value, precision) {
    var precision = precision || 0,
        power = Math.pow(10, precision),
        absValue = Math.abs(Math.round(value * power)),
        result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));

    if (precision > 0) {
        var fraction = String(absValue % power),
            padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
        result += '.' + padding + fraction;
    }
    return result;
}

Read the details of repeating a character using an array constructor here if you are curious as to why I added the "+ 1".

@alan 2013-09-20 14:48:51

Passing in a value of 708.3333333333333 with a precision of 2 or 3 results in a return value of 708.00 for me. I need this for 2 decimal places, in Chrome and IE 9 .toFixed(2) met my needs.

@hiway 2014-06-04 03:49:25

this is not a common way, e.g, toFixed(16.775, 2) return 16.77. Convert number to String then convert is the only way.

@Matt 2014-10-20 02:40:13

There is a bug with this method: toFixed(-0.1111, 2) returns 0.11, i.e. the negative sign is lost.

@Elias Zamaria 2014-10-20 17:05:28

@Matt, thanks for pointed that out. I fixed the bug.

@Artur Barseghyan 2015-03-25 17:01:45

Works great, except for that I have added parseFloat(result) at the end. Worth an edit.

@de.la.ru 2012-11-16 17:04:05

There's always a better way for doing things.

var number = 51.93999999999761;

I would like to get four digits precision: 51.94

just do:

number.toPrecision(4);

the result will be: 51.94

@JohnnyBizzle 2016-08-16 08:48:55

And what if you add 100? Do you need to change it to number.toPrecision(5)?

@ReSpawN 2017-01-03 08:51:39

Yes. 31.939383.toPrecision(4) > "31.94" / 131.939383.toPrecision(4) > "131.9"

@Christoph 2010-02-08 11:48:37

Hopefully working code (didn't do much testing):

function toFixed(value, precision) {
    var precision = precision || 0,
        neg = value < 0,
        power = Math.pow(10, precision),
        value = Math.round(value * power),
        integral = String((neg ? Math.ceil : Math.floor)(value / power)),
        fraction = String((neg ? -value : value) % power),
        padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');

    return precision ? integral + '.' +  padding + fraction : integral;
}

@Elias Zamaria 2010-05-25 23:28:41

Your code has a bug. I tried toFixed(2.01, 4) and got a result of "2.100". If I ever find a way to fix it, I will post it as an answer to this question.

@Christoph 2010-05-27 14:32:14

@mikez302: the padding computation was off by one; should work now, but feel free to bug me again if it's still broken...

@SublymeRick 2013-01-07 10:40:28

Very strange. When I run this fuction with the firebug console open in firefox 17 it freezes the whole browser like js is caught in an endless loop. Even if i do not console.log the output. If I do not have firebug activated the bug does not occur.

@SublymeRick 2013-01-07 10:42:37

Update, i ran it in chrome and i get: Uncaught RangeError: Maximum call stack size exceeded in regards to the toFixed function call.

@Christoph 2013-01-07 11:01:34

@SublymeRick: I have no idea why this happens; shot in the dark: try renaming the function...

@AaA 2017-11-06 02:15:04

@Christoph, I believe it is happening because of stacking all vars and calculations with comma on a single var statement. It breaks the debugger, but works in browser.I had similar case with a larger script, if I remember correctly on Firefox 42

@Guffa 2010-02-08 11:27:23

That's not a rounding ploblem, that is a display problem. A number doesn't contain information about significant digits; the value 2 is the same as 2.0000000000000. It's when you turn the rounded value into a string that you have make it display a certain number of digits.

You could just add zeroes after the number, something like:

var s = number.toString();
if (s.indexOf('.') == -1) s += '.';
while (s.length < s.indexOf('.') + 4) s += '0';

(Note that this assumes that the regional settings of the client uses period as decimal separator, the code needs some more work to function for other settings.)

@mpen 2010-09-01 06:50:40

What's wrong with .toFixed(dec)?

@Bat_Programmer 2011-09-19 01:58:21

toFixed is buggy..for instance the decimal: 1.02449999998 if u do dec.toFixed(4) => 1.0244. It should have been 1.0245 instead.

@pauloya 2011-12-15 17:11:01

@deepeshk But what would be the problem with using toFixed() to pad decimals at the end, after rounding?

@Matt Ball 2012-03-13 14:40:04

@deepeshk in what browser? Just tried it in Chrome 17 and 1.02449999998.toFixed(4) correctly returns 1.0245.

@Mark Tomlin 2013-05-21 00:28:01

@Mark got most of the answer, but after some research you need to call it like this, Number(float).toFxied(places);.

@Guffa 2013-05-21 01:14:02

@MarkTomlin: Then it seems that you have a string instead of a number.

@Mark Tomlin 2013-05-21 03:32:18

@Guffa thanks' for the clarification, I'm kinda fumbling my way through JavaScript programming right now. +1.

@alan 2013-09-20 14:50:01

As an FYI, if you only need precision to 2 decimal places .toFixed works for both IE and Chrome.

@robocat 2015-05-07 03:57:40

.toFixed() works brilliantly in modern browsers (I tested Chrome, Firefox, IE11, IE8). @Bat_Programmer - please clarify which browsers you think have that bug.

@Guffa 2015-05-07 07:58:23

@robocat 2015-05-26 22:45:54

.toFixed() is fixed in IE8+ (my testing) but apparently buggy in IE7 (as per @Guffa link in comment above - thank you). So use toFixed() unless you need to support IE7 ;-)

@robocat 2015-05-26 23:01:44

Do NOT USE this answer because it has serious bugs: it gives incorrect answers: NaN -> NaN.000, Infinity -> Infinity.000, 9e60 -> 9E60.000, 0.000001 -> 0.000001 (0.000001.toFixed(3) correctly gives 0.000).

@Guffa 2015-05-27 00:50:50

@robocat: Are you serious?

@robocat 2015-05-28 03:40:52

@Guffa - .toFixed() works correctly in IE8+. e.g. I just run IE8 using the example from the link of (0.595).toFixed(2) and got correct answer of 0.60. Your code is broken for corner cases (the few I thought of from the top of my head with a few minutes testing, I could probably find other things wrong with it), and is not suitable for production code IMHO.

@Guffa 2015-05-28 08:29:43

@robocat: You are looking for something that I never claimed that the code would be. Besdies, you can just as easily find corner cases where toFixed is broken, for example (1000000000000000000000).toFixed(3) returns 1e+21 not 1000000000000000000000.000.

@Paul 2010-02-08 11:29:38

Here's a link to a Javascript sprintf,

http://www.webtoolkit.info/javascript-sprintf.html

A call to sprintf() is one rounding methodology in perl, but javascript doesn't have that function natively.

http://perldoc.perl.org/functions/sprintf.html

Does that help?

@Roy Tinker 2011-10-01 00:37:48

That library is using the built-in toFixed function.

Related Questions

Sponsored Content

63 Answered Questions

[SOLVED] Round to at most 2 decimal places (only if necessary)

54 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

76 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5598447 View
  • 6939 Score
  • 76 Answer
  • Tags:   javascript arrays

47 Answered Questions

48 Answered Questions

[SOLVED] Validate decimal numbers in JavaScript - IsNumeric()

26 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

26 Answered Questions

[SOLVED] Format number to always show 2 decimal places

29 Answered Questions

[SOLVED] How to round a number to n decimal places in Java

Sponsored Content