Javascript: formatting a rounded number to N decimals

JavascriptMathRoundingDecimal Point

Javascript Problem Overview


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

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

console.log(roundNumber(0.1 + 0.2, 2));
console.log(roundNumber(2.1234, 2));

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 Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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()][1] [1]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math/round

Solution 6 - Javascript

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 https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places/34796988 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);
}

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhojuView Question on Stackoverflow
Solution 1 - JavascriptDavidView Answer on Stackoverflow
Solution 2 - JavascriptElias ZamariaView Answer on Stackoverflow
Solution 3 - JavascriptGuffaView Answer on Stackoverflow
Solution 4 - Javascriptde.la.ruView Answer on Stackoverflow
Solution 5 - JavascriptJohnnyBizzleView Answer on Stackoverflow
Solution 6 - JavascriptGeorge BirbilisView Answer on Stackoverflow
Solution 7 - JavascriptChristophView Answer on Stackoverflow
Solution 8 - JavascriptKRISHNA TEJAView Answer on Stackoverflow
Solution 9 - JavascriptJuan CarreyView Answer on Stackoverflow