Javascript round to 6 decimal places

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

function roundNumber(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?

Javascript round to 6 decimal places

asked Feb 8, 2010 at 11:19

3

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...

Javascript round to 6 decimal places

נשמה קשוחה

17.8k10 gold badges66 silver badges98 bronze badges

answered Aug 18, 2011 at 7:08

DavidDavid

4,0662 gold badges22 silver badges30 bronze badges

4

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".

answered May 25, 2010 at 23:34

Javascript round to 6 decimal places

Elias ZamariaElias Zamaria

91.4k31 gold badges112 silver badges143 bronze badges

4

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.)

answered Feb 8, 2010 at 11:27

GuffaGuffa

673k108 gold badges718 silver badges991 bronze badges

14

There's always a better way for doing things. Use toPrecision -

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

Brian Burns

18.7k8 gold badges79 silver badges70 bronze badges

answered Nov 16, 2012 at 17:04

Javascript round to 6 decimal places

de.la.rude.la.ru

2,7441 gold badge25 silver badges32 bronze badges

2

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()

jaggedsoft

3,6171 gold badge32 silver badges40 bronze badges

answered Aug 16, 2016 at 9:02

Javascript round to 6 decimal places

JohnnyBizzleJohnnyBizzle

9732 gold badges17 silver badges31 bronze badges

0

This works for rounding to N digits (if you just want to truncate to N digits remove the Math.round call and use the Math.trunc one):

function roundN(value, digits) {
   var tenToN = 10 ** digits;
   return /*Math.trunc*/(Math.round(value * tenToN)) / tenToN;
}

Had to resort to such logic at Java in the past when I was authoring data manipulation E-Slate components. That is since I had found out that adding 0.1 many times to 0 you'd end up with some unexpectedly long decimal part (this is due to floating point arithmetics).

A user comment at Format number to always show 2 decimal places calls this technique scaling.

Some mention there are cases that don't round as expected and at http://www.jacklmoore.com/notes/rounding-in-javascript/ this is suggested instead:

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

answered Jun 17, 2019 at 13:38

George BirbilisGeorge Birbilis

2,6762 gold badges31 silver badges34 bronze badges

1

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;
}

answered Feb 8, 2010 at 11:48

ChristophChristoph

160k36 gold badges177 silver badges234 bronze badges

6

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

answered Sep 8, 2017 at 19:24

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;
}

answered Apr 16, 2014 at 7:57

Javascript round to 6 decimal places

Juan CarreyJuan Carrey

6861 gold badge6 silver badges13 bronze badges

2

How do you round to 6 decimal places in JavaScript?

JavaScript Demo: Math.round().
console. log(Math. round(0.9)); // expected output: 1. ​.
console. log(Math. round(5.95), Math. round(5.5), Math. round(5.05)); // expected output: 6 6 5. ​.
console. log(Math. round(-5.05), Math. round(-5.5), Math. round(-5.95)); // expected output: -5 -5 -6. ​.

How do you round 6 decimal places?

There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.

How do you round to a certain decimal places in JavaScript?

The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.

How do I limit the number of decimal places in JavaScript?

To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places.