怎么解决javascript小数相减会出现一长串的小数位数?
找了下资料都说用parseFloat(11.3-10.1)可以解决这个问题,
可是出来的还是1.200000000000001
我试了下还是不行啊!!!
求指导····
用toFixed()函数吧
[解决办法]
String.prototype.toFloat=Number.prototype.toFloat=function toFloat(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))