我有下面的代码。我想让它这样,如果price_result等于一个整数,比如10,然后我想加两位小数点后。所以10就是10.00。 如果等于10.6,就是10.60。不知道该怎么做。

price_result = parseFloat(test_var.split('$')[1].slice(0,-1));

当前回答

parseFloat(parseFloat(amount).toFixed(2))

你必须解析两次。第一次是将字符串转换为浮点数,然后将其固定为两个小数(但toFixed返回一个字符串),最后再次解析它。

其他回答

下面是对我有效的解决方案

parseFloat(value)

如果你不想四舍五入,请使用下面的函数。

function ConvertToDecimal(num) {
    num = num.toString(); //If it's not already a String
    num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
   alert('M : ' +  Number(num)); //If you need it back as a Number    
}

您可以使用.toFixed()来表示浮点值2位

Exampale

let newValue = parseFloat(9.990000).toFixed(2) / /输出 9.99

来自洛达什的西尔可能是最好的

_.ceil("315.9250488",2) 
_.ceil(315.9250488,2) 
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)

也会工作与一个数字,它是安全的

如果你需要性能(游戏邦注:比如在游戏中):

Math.round(number * 100) / 100

它大约是parseFloat(number.toFixed(2))速度的100倍。

http://jsperf.com/parsefloat-tofixed-vs-math-round