How to format a float in javascript?

Viewed 541521

In JavaScript, when converting from a float to a string, how can I get just 2 digits after the decimal point? For example, 0.34 instead of 0.3445434.

14 Answers

There are functions to round numbers. For example:

var x = 5.0364342423;
print(x.toFixed(2));

will print 5.04.

EDIT: Fiddle

var result = Math.round(original*100)/100;

The specifics, in case the code isn't self-explanatory.

edit: ...or just use toFixed, as proposed by Tim Büthe. Forgot that one, thanks (and an upvote) for reminder :)

Be careful when using toFixed():

First, rounding the number is done using the binary representation of the number, which might lead to unexpected behaviour. For example

(0.595).toFixed(2) === '0.59'

instead of '0.6'.

Second, there's an IE bug with toFixed(). In IE (at least up to version 7, didn't check IE8), the following holds true:

(0.9).toFixed(0) === '0'

It might be a good idea to follow kkyy's suggestion or to use a custom toFixed() function, eg

function toFixed(value, precision) {
    var power = Math.pow(10, precision || 0);
    return String(Math.round(value * power) / power);
}
var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding

If you want the string without round you can use this RegEx (maybe is not the most efficient way... but is really easy)

(2.34567778).toString().match(/\d+\.\d{2}/)[0]
// '2.34'

countDecimals = value => {
    if (Math.floor(value) === value) return 0;
    let stringValue = value.toString().split(".")[1];
    if (stringValue) {
      return value.toString().split(".")[1].length
        ? value.toString().split(".")[1].length
        : 0;
    } else {
      return 0;
    }
  };
  
formatNumber=(ans)=>{
    let decimalPlaces = this.countDecimals(ans);
    ans = 1 * ans;
    if (decimalPlaces !== 0) {
      let onePlusAns = ans + 1;
      let decimalOnePlus = this.countDecimals(onePlusAns);
      if (decimalOnePlus < decimalPlaces) {
        ans = ans.toFixed(decimalPlaces - 1).replace(/\.?0*$/, "");
      } else {
        let tenMulAns = ans * 10;
        let decimalTenMul = this.countDecimals(tenMulAns);
        if (decimalTenMul + 1 < decimalPlaces) {
          ans = ans.toFixed(decimalPlaces - 1).replace(/\.?0*$/, "");
        }
      }
    }
}

I just add 1 to the value and count the decimal digits present in the original value and the added value. If I find the decimal digits after adding one less than the original decimal digits, I just call the toFixed() with (original decimals - 1). I also check by multiplying the original value by 10 and follow the same logic in case adding one doesn't reduce redundant decimal places. A simple workaround to handle floating-point number rounding in JS. Works in most cases I tried.

Related