Har*_*OTA 25 javascript floating-point comparison numbers
我有这个JavaScript函数:
Contrl.prototype.EvaluateStatement = function(acVal, cfVal) {
var cv = parseFloat(cfVal).toFixed(2);
var av = parseFloat(acVal).toFixed(2);
if( av < cv) // do some thing
}
Run Code Online (Sandbox Code Playgroud)
当我比较浮点数av=7.00
和cv=12.00
结果7.00<12.00
是false
!
有什么想法吗?
sec*_*ond 36
toFixed返回一个字符串,并且您正在比较两个结果字符串.从词汇上看,12比1来自7比12比7.
我猜你想比较一下:
(Math.round(parseFloat(acVal)*100)/100)
Run Code Online (Sandbox Code Playgroud)
它舍入到小数点后两位
Edw*_*ard 10
比较浮点数与精度:
var precision = 0.001;
if (Math.abs(n1 - n2) <= precision) {
// equal
}
else {
// not equal
}
Run Code Online (Sandbox Code Playgroud)
UPD:或者,如果数字之一是精确的,则将精度与相对误差进行比较
var absoluteError = (Math.abs(nApprox - nExact)),
relativeError = absoluteError / nExact;
return (relativeError <= precision);
Run Code Online (Sandbox Code Playgroud)
小智 6
Math.fround() 函数返回数字最接近的 32 位单精度浮点表示形式。
因此是比较 2 个浮点数的最佳选择之一。
if (Math.fround(1.5) < Math.fround(1.6)) {
console.log('yes')
} else {
console.log('no')
}
>>> yes
// More examples:
console.log(Math.fround(0.9) < Math.fround(1)); >>> true
console.log(Math.fround(1.5) < Math.fround(1.6)); >>> true
console.log(Math.fround(0.005) < Math.fround(0.00006)); >>> false
console.log(Math.fround(0.00000000009) < Math.fround(0.0000000000000009)); >>> false
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
39167 次 |
最近记录: |