k6t back
k6t back

Reputation: 85

convert decimal to string without removing 0 "zero(s)"?

nStr    =   12.00;
alert(typeof(nStr));// getting number
x = nStr.split('.');
// Other than string Split function Through an error,
nStr    =   12.00;
nStr    +=  '';
alert(typeof(nStr));// getting string
x       =   nStr.split('.');
x1      =   x[0];
x2      =   x.length > 1 ? '.' + x[1] : '';
alert(x1+x2);

//Expected Output is 12.00

I got the temp output coding ( its not optimized coding)

nStr += '';
x = nStr.split('.');
x1  = x[0];
x[1]= (x[1].length == 1) ? '.' + x[1] + '0' : '.' + x[1];
x2  = x.length > 1 ? x[1] : '.00';
alert(x1+x2);               //  12.00

Upvotes: 1

Views: 3347

Answers (2)

user1006565
user1006565

Reputation:

Instead of writing

nStr    =   12.00;

u can write something like this

nStr    =   "12.00";

Upvotes: 0

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

12.00 is 12 you can't change that fact.

Looks like what you are after is the toFixed() method of JavaScript:

nStr    =   12;
alert(nStr.toFixed(2));

This will alert "12.00" as you want. The number passed to the method determines how many digits after the decimal point will be displayed.

Worth mentioning is that the toFixed method will also round numbers, for example if in the above example nStr will be 12.5283 it will show 12.53 in the alert.

Upvotes: 5

Related Questions