Reputation: 13
I wanted feedback on why toFixed would not work in my JS alert when attached to the user input var usergb. Was a curious thing. I've been encouraged to post and I did not see any other questions out here regarding toFixed issues with user-input vars.
var downloadspeed = function () {
var usergb = prompt("How many gigabytes do you wish to download at 56 kilobits per second?");
console.log(usergb);
var hours = (usergb*8388608)/201600;
console.log(hours);
var days = (usergb*8388608)/4838400;
console.log(days);
//below in the alert is where you will see it, after the first concatenated string, I'd like to type usergb.toFixed(2) but it won't take.
alert("The number of hours it will take to download a " + usergb + " GB file at 56 kilobits per second is " + hours.toFixed(2) + " hours. This might be a big number. So, in terms of days to download, it'll take " + days.toFixed(2) + " days to download. This is why we have faster broadband speeds nowadays and why we have video streaming.");
}
downloadspeed();
The error I get is that it is not a function.
Grazie, Lou
Upvotes: 1
Views: 283
Reputation: 1
toFixed is a method on a Number ...
prompt returns a String
try parseFloat(usergb).toFixed(2)
Upvotes: 2
Reputation: 166
You can parse the input in the Number type. Example plunkr
var downloadspeed = function() {
var input = prompt("How many gigabytes do you wish to download at 56 kilobits per second?");
var usergb = new Number(input);
if(isNaN(usergb))
{
alert("You must input a number");
return;
}
console.log(usergb);
var hours = (usergb * 8388608) / 201600;
console.log(hours);
var days = (usergb * 8388608) / 4838400;
console.log(days);
//below in the alert is where you will see it, after the first concatenated string, I'd like to type usergb.toFixed(2) but it won't take.
alert("The number of hours it will take to download a " + usergb + " GB file at 56 kilobits per second is " + hours.toFixed(2) + " hours. This might be a big number. So, in terms of days to download, it'll take " + days.toFixed(2) + " days to download. This is why we have faster broadband speeds nowadays and why we have video streaming.");
}
downloadspeed();
Upvotes: 0
Reputation: 11983
You need to cast the input as a number:
var usergb = +prompt("How many gigabytes do you wish to download at 56 kilobits per second?");
Upvotes: 0
Reputation: 181
You have to use toFixed()
on the number:
parseFloat(usergb).toFixed(2)
The prompt function returns a string, you can not use toFixed()
on strings, only on numbers.
Upvotes: 1