例如parseFloat(11.3-10.1) 或者直接11.3-10.1 出来的结果是1.200000000000001
最终只能取个相对理想的方法,但是还是没有达到预期希望的那样把
就是在你相减完之后,进行小数点的取舍
parseFloat(11.3-10.1).toFixed(1)
例外js里面的字符串转换为数字的话,可以直接通过*1来实现
例如:parseFloat(“1.27”*1 - “1.11”*1).toFixed(2)
论坛里一个牛人给出的总结方法:
String.prototype.toFloat=Number.prototype.toFloat=function(decimalPlace,isRoundUp){
/// <summary>
/// String,Number原型扩展:保留指定的小数位数[可选择是否使用四舍五入]
/// </summary>
/// <param name="decimalPlace">需要保留的小数位</param>
/// <param name="isRoundUp">是否是舍五入[可选项:默认true]</param>
/// <returns>数据类型:Number(浮点数)</returns>
decimalPlace = decimalPlace || 0,
isRoundUp = Object.prototype.toString.call(isRoundUp).match(/^\[object\s(.*)\]$/)[1].toLowerCase()=='boolean' ? isRoundUp : !0;
try{
var res = isRoundUp
? (this*1).toFixed(decimalPlace)
: this.toString().replace(new RegExp("([0-9]+\.[0-9]{"+decimalPlace+"})[0-9]*","g"),"$1");
return isNaN(res*1) ? this: res;
}catch(e){
return isNaN(this*1) ? this : this*1;//防止小数位数字越界
}
}
alert(parseFloat(11.3-10.1222222).toFloat(2,!0))