+ 2

Getting nan while using parseFloat and number with prompt in js

Why parseFloat with prompt outputs nan in js? Here's the ex... // Using parseFloat with prompt const weightInput = prompt("Enter your weight in kg:"); const parsedWeightFloat = parseFloat(weightInput); console.log("Parsed weight using parseFloat:", parsedWeightFloat); // Using Number with prompt const heightInput = prompt("Enter your height in cm:"); const parsedHeightNumber = Number(heightInput); console.log("Parsed height using Number:", parsedHeightNumber); // It outputs nan when giving input as strings like "5" etc , parseFloat should check if that string is convertable instead of nan.

31st Jan 2024, 7:42 PM
Niraj Kumar
Niraj Kumar - avatar
13 Answers
+ 1
let f = ' 5.5 ' let f1 = ' "5.5" ' console.log(parseFloat(f)) //5.5 console.log(parseFloat(f1))//NaN //prompt adds " " to your prompt input. So there is no need to add it yourself. To see the raw string prompt() returns: console.log(JSON.stringify(prompt()))
1st Feb 2024, 6:12 AM
Bob_Li
Bob_Li - avatar
+ 3
Stefanoo Bob_Li I got it, when I enter a no. with quotation marks in prompt with parseFloat it's parsing the entire strings since quotes are non-numeric it's giving NaN as output. thanks:)
1st Feb 2024, 5:39 AM
Niraj Kumar
Niraj Kumar - avatar
+ 2
I don't get nan. It seems to work fine. I testet integer and float.
31st Jan 2024, 8:31 PM
Stefanoo
Stefanoo - avatar
+ 2
Bob_Li yes but parseFloat function is designed to handle strings representing numbers, so shouldn't it should parse the numeric part of the string?
1st Feb 2024, 5:32 AM
Niraj Kumar
Niraj Kumar - avatar
+ 1
"It's strange because I'm still getting NaN. If only there were a way to send a screenshot or some output, I would."
31st Jan 2024, 11:26 PM
Niraj Kumar
Niraj Kumar - avatar
+ 1
Wow, I never imagined a user would enter quoted numbers or text, unless they r told to do so. This was pretty interesting.
1st Feb 2024, 7:31 PM
arturop200
arturop200 - avatar
0
You can add a screenshot to your feed. You find your feed in the community section.
1st Feb 2024, 12:13 AM
Stefanoo
Stefanoo - avatar
0
Niraj Kumar are you typing "5" in the prompt? you should not add the quotation marks. prompt input are already string by default.
1st Feb 2024, 4:18 AM
Bob_Li
Bob_Li - avatar
0
This loop will continue prompting the user for input until a valid number is entered. you can add additional validation logic to check if the input is NaN and prompt the user again until they provide a valid input
1st Feb 2024, 11:57 AM
Code With Nouman
Code With Nouman - avatar
0
Hii
2nd Feb 2024, 6:18 AM
Kiran Gedela
Kiran Gedela - avatar
2nd Feb 2024, 6:18 AM
Kiran Gedela
Kiran Gedela - avatar
0
Cool guy python
2nd Feb 2024, 11:57 AM
Kabiru Mohammed
Kabiru Mohammed - avatar