Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple toFixed(2) issue 1

Status
Not open for further replies.

lifelineamerica

Programmer
Aug 9, 2006
23
US
I'm trying to display values selected via radio button. It works fine as:

function GetSelectedItem() {
var thefrm = document.forms['showtimes'].elements;
var theans = thefrm['time_id[]'];
for(i=0;i<theans.length;i++) {
theel = theans;
tnum=theel.value
if(theel.checked == true){
document.getElementById('outputText').innerHTML = "$" + (tnum);
}
}
}


I want to output the value in nice decimal format so I changed the code to:

function GetSelectedItem() {
var thefrm = document.forms['showtimes'].elements;
var theans = thefrm['time_id[]'];
for(i=0;i<theans.length;i++) {
theel = theans;
tnum=theel.value
result=tnum.toFixed(2);
if(theel.checked == true){
document.getElementById('outputText').innerHTML = "$" + (result);
}
}
}


I get the following error:
TypeError: Result of expression 'tnum.toFixed' [undefined] is not a function.

Apparenttly it's not letting me run the toFixed() function on a variable?
 
Input values are stored as strings, and strings do not have a toFixed method. Convert the string to a number first by using parseFloat:

Code:
var str = '123.45678';
alert(str.toFixed(2));   // TypeError: Object 123.45678 has no method 'toFixed'

var strNum = parseFloat(str);
alert(strNum.toFixed(2));    // Shows '123.46'

Hope this helps,

Dan


Coedit Limited - Delivering standards compliant, accessible web solutions

[blue]@[/blue] Code Couch:
[blue]@[/blue] Twitter:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top