2011-11-16 63 views
1
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 

我得到临时输出编码(它不是最优化的编码)将十进制转换为字符串而不删除0“零(s)”?

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 
+0

您正在寻找的printf的equilivant()。这是http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format – g19fanatic

回答

5

12.00 12,你不能改变的事实。

看起来,你是后什么是JavaScript的toFixed()方法:

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

只要你想这将提醒“12.00”。传递给该方法的数字将确定显示小数点后的数字。

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

+0

是的重复!谢谢你的帮助!!! –

+0

干杯,很高兴我能帮上忙。 :-) –

0

而是写

nStr = 12.00; 

的ü可以写这样的事情

nStr = "12.00"; 
相关问题