sanjeev
sanjeev

Reputation: 4621

parseFloat not working with zero after decimal

I have a text box , form the text box I need to pass a float value to a api.

Now things are working fine when I have value inside the text box as "18.575" or "18.09483".

But in case the value is "18.000" things are not working. I understand that 18.000 is same as 18 but I need the precision digits.

So problem is I need exact 18.00 in JavaScript and not 18

I tried

a) parseFloat

  parseFloat("18.000");  // I get 18

b) toFixed

 (18).toFixed(2) // I get `"18.00"` but it is string and doesn't solve the purpose.

c) Number

Number("18.00") // gives 18 and not 18.00

Thanks in advance for help

Upvotes: 1

Views: 3584

Answers (2)

Shankaranand
Shankaranand

Reputation: 67

Try

parseFloat((18).toFixed(2))

Upvotes: -1

georg
georg

Reputation: 214949

Native JSON doesn't provide a way to specify floats precision, you can hack around this by manipulating encoded json string, like

    data = {
        something: 18
    };
    
    json = JSON.stringify(data, function(key, val) {
        if(typeof(val) === 'number')
            return '<<<' + val.toFixed(3) + '>>>';
        return val;
    }).replace(/"<<<|>>>"/g, '');

    document.write(json)

which is kinda silly, but works

Upvotes: 3

Related Questions