我曾经使用String函数将数字转换为字符串,但我发现像1.0的情况,结果是"1",但我期望"1.0".我知道1和1.0在Javascript中基本相同.但是你通常如何修补它以支持我的情况?
更新:请不要误解我的问题,我想保留其他默认行为,String这意味着toFixed不正确的解决方案.例如
1 ==> "1"
1.0 ==> "1.0"
1.00 ==> "1.00"
1.2334 ==> "1.2334"
Run Code Online (Sandbox Code Playgroud)
您可以使用"toFixed"函数来执行此操作,例如:
var num = 1.2345;
var n = num.toFixed(1);
Run Code Online (Sandbox Code Playgroud)
您可以将其与检查结合起来查看数字是否为整数:
function numToString(num)
{
if (num % 1 === 0)
return num.toFixed(1);
else
return num.toString();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
959 次 |
| 最近记录: |