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?

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

נשמה קשוחה

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

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

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

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

Chủ Đề