为什么 Firebug 说 tofix()不是一个函数?

我使用的是 jQuery 1.7.2和 jQuery UI 1.9.1,我在一个滑块中使用了下面的代码( http://jqueryui.com/slider/)

我有一个函数,它应该测试两个值,并根据两个值之间的差异重新格式化它们(到适当的小数位)。如果差值大于10,我将解析出整数。如果差值大于5,则应保持为小数点后一位。其他的,我会保留两个小数。

当我输入两个差异小于或等于10的值时,我使用 toFixed()函数。在 Firebug 中,我看到一个错误:

TypeError: Low.toFixed is not a function
Low = Low.toFixed(2);

我做错了什么简单的事吗?

这是我的代码:

var Low = $SliderValFrom.val(),
High = $SliderValTo.val();


// THE NUMBER IS VALID
if (isNaN(Low) == false && isNaN(High) == false) {
Diff = High - Low;
if (Diff > 10) {
Low = parseInt(Low);
High = parseInt(High);
} else if (Diff > 5) {
Low = Low.toFixed(1);
High = High.toFixed(1);
} else {
Low = Low.toFixed(2);
High = High.toFixed(2);
}
}
218169 次浏览

That is because Low is a string.

.toFixed() only works with a number.


Try doing:

Low = parseFloat(Low).toFixed(..);

toFixed isn't a method of non-numeric variable types. In other words, Low and High can't be fixed because when you get the value of something in Javascript, it automatically is set to a string type. Using parseFloat() (or parseInt() with a radix, if it's an integer) will allow you to convert different variable types to numbers which will enable the toFixed() function to work.

var Low  = parseFloat($SliderValFrom.val()),
High = parseFloat($SliderValTo.val());

Low is a string.

.toFixed() only works with a number.

A simple way to overcome such problem is to use type coercion:

Low = (Low*1).toFixed(..);

The multiplication by 1 forces to code to convert the string to number and doesn't change the value.

In a function, use as

render: function (args) {
if (args.value != 0)
return (parseFloat(args.value).toFixed(2));




},

You need convert to number type:

(+Low).toFixed(2)

parseFloat() will return NaN for empty string, why not using Number() function instead?

Values of other types can be converted to numbers using the Number() function.

parseFloat('').toFixed(2) // "NaN"
Number('').toFixed(2) // "0.00"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

Low = Number(Low).toFixed(1);

add the Number function to convert Low into a number.