November 20th, 2013 at 1:48 pm

Decimal number formatter in JavaScript

Today we’ll build a decimal number formatter for JavaScript. A common use case is the display of numbers with a fixed amount of digits (like a price amount), even if the actual value has more or less digits.

This is a bit more complicated that it may seem at first glance: The internal representation of a float value is in some cases not what you see, but a weird number such as 100.000000000023. Therefore it’s not sufficient to round the vaule and chop off a bit at the end. Our approach is a bit more complicated, but bullet-proof. At the end, we receive a string (NB: not a float!) that is the exact representation of the figure we want to show.

Note: We are using the pad() function that has been introduced in an earlier post.

 
/**
 * Formats float values to a string representation with a fixed number of decimals
 *
 * @param val the numeric value to format (required)
 * @param _decimals number of decimals (optional, default: 2)
 * @param _sep the decimal separator (optional, default: ".")
 *
 */
var numberFormat = function(val, _decimals, _sep)
{
    var
        decimals = _decimals || 2,
        sep = _sep || '.',
        floatVal = parseFloat(val) || 0,
        intpart = Math.floor(floatVal),
        factor = Math.pow(10, decimals),
        fractpart = floatVal*factor - intpart*factor;
 
    fractpart = pad(Math.round(fractpart), decimals, '0');
 
    return '' + intpart + sep + fractpart;
};
// Some tests
alert(numberFormat(234.2247)); // "234.22"
alert(numberFormat(234.2)); // "234.20"
alert(numberFormat(234.2247, 3)); // "234.225"
alert(numberFormat(234.2247, 2, ',')); // "234,22"

Leave a Comment