-1

I have a situation here in javascript

**Value**       **Expected**  **toFixed(2)**
var a = 0.0273 |  0.0273     |  0.03(X)
var b = 0.8    |  0.80       |  0.80
var b = 53.7   | 53.70       | 53.70

When four digits come after the decimal point, leave it as it is, but if a single digit comes, a zero should be appended.

toFixed() method didn't help me much.

Re Captcha
  • 3,125
  • 2
  • 22
  • 34
gauti
  • 527
  • 1
  • 6
  • 16
  • this is your answer http://stackoverflow.com/a/15266797/1570534 – Hanky Panky Aug 24 '15 at 08:31
  • 1
    you can split the number on the point : `var array=a.toString().split(".")` and then you can find if you need `toFixed()` or not : `if(array[1].length<2){ a.toFixed(2); } // no else is needed` – Majed DH Aug 24 '15 at 08:31

1 Answers1

0

First you check the amount of decimals with:

var countDecimals = function (value) { 
    if ((value % 1) != 0) 
        return value.toString().split(".")[1].length;  
    return 0;
};

https://stackoverflow.com/a/17369384/1870760

Then you check if it's 4 or not and parse it with toFixed:

var a = 0.0273;

    var countDecimals = function (value) { 
        if ((value % 1) != 0) 
            return value.toString().split(".")[1].length;  
        return 0;
    };

if(countDecimals(a) < 4)
  a = (Math.round(a * 100) / 100).toFixed(2);

alert(a)
Community
  • 1
  • 1
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122