将十进制转换为字符串而不删除0“零(s)”?

时间:2011-11-16 12:10:54

标签: javascript jquery

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

我得到了临时输出编码(它没有优化编码)

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

2 个答案:

答案 0 :(得分:5)

12.00 12你无法改变这一事实。

看起来你所追求的是JavaScript的toFixed()方法:

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

这将根据需要提醒“12.00”。传递给方法的数字决定了小数点后的位数。

值得一提的是,toFixed方法也会对数字进行舍入,例如,如果在上面的示例中nStr将为12.5283,它将在警报中显示12.53。

答案 1 :(得分:0)

而不是写

nStr    =   12.00;
你可以写这样的东西

nStr    =   "12.00";