Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Firebug say toFixed() is not a function?

Tags:

javascript

I am using jQuery 1.7.2 and jQuery UI 1.9.1. I am using the code below within a slider. (http://jqueryui.com/slider/)

I have a function that should test two values and depending on the difference between the two values reformat them (to the appropriate decimal place). If the difference is greater than 10, I will parse out the integer. If the difference is greater than 5, it should keep one decimal. Everything else, I will keep two decimals.

When I enter two values that have a difference that is ten or less, I use the toFixed() function. And, in Firebug, I see an error:

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

Is there something simple that I am doing wrong?

Here is my code:

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); } } 
like image 531
Evik James Avatar asked Dec 27 '12 18:12

Evik James


People also ask

Why is toFixed not working?

The "toFixed is not a function" error occurs when the toFixed() method is called on a value that is not a number . To solve the error, either convert the value to a number before calling the toFixed method or only call the method on numbers.

How do you convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.


2 Answers

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()); 
like image 176
jeremy Avatar answered Sep 19 '22 12:09

jeremy


That is because Low is a string.

.toFixed() only works with a number.


Try doing:

Low = parseFloat(Low).toFixed(..); 
like image 31
Naftali Avatar answered Sep 17 '22 12:09

Naftali