JavaScript 中的浮点数比较

4

为什么 100 >= 99.2 是错误的呢?这是怎么回事?

var ls = parseFloat(("100").replace(",", ".")).toFixed(1);
var val = parseFloat(("99,2").replace(",", ".")).toFixed(1);
alert(ls >= val); /*=> result is false  ...but it should be true */

UI文化是nl-BE

JSFiddle: http://jsfiddle.net/Ed6VY/

1个回答

5

toFixed 的结果是一个字符串。字符串会逐个字符进行比较。因为 "9""1" 之后,所以 "99.2" 大于 "100.0"


@OP:您可以使用alert(typeof ls);来验证它是一个字符串。 - h2ooooooo
请参考此处更详细的解释:https://dev59.com/-3E95IYBdhLWcg3whODK - Michiel Cornille

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接