如何验证价格字段输入的数值是否以.99结尾?
判断数值是否以.99结尾的方法
你遇到的问题本质是JS浮点数精度误差导致的——像19.99这类小数在二进制存储中是近似值,直接用price % 1会得到接近0.99但有误差的结果,比如19.99 % 1可能返回0.989999999999998,导致判断失效。
下面给两种可靠的解决方法:
方法一:字符串直接判断
把数值转成字符串后,直接检查是否以.99结尾,简单直观:
function isPriceEndsWith99(price) { return price.toString().endsWith('.99'); } // 测试示例 console.log(isPriceEndsWith99(9.99)); // true console.log(isPriceEndsWith99(19.99)); // true console.log(isPriceEndsWith99(20)); // false console.log(isPriceEndsWith99(100.99)); // true
注意:如果输入的数值存在多余小数位(比如9.990),可以先格式化到两位小数再判断。
方法二:数值精度处理后判断
通过乘以100转成整数,再取余100判断是否等于99,同时用Math.round规避浮点数精度误差:
function isPriceEndsWith99(price) { const totalCents = Math.round(price * 100); return totalCents % 100 === 99; } // 测试示例 console.log(isPriceEndsWith99(9.99)); // true console.log(isPriceEndsWith99(19.99)); // true console.log(isPriceEndsWith99(20.00)); // false console.log(isPriceEndsWith99(5.99)); // true
这种方法更适合严格的数值场景,能避免字符串转换可能带来的异常(比如科学计数法表示的大数值)。
内容的提问来源于stack exchange,提问作者orriioon
相关产品推荐
相关产品推荐

