Categories > Coding > Javascript >
Floating-Point Conversion Precision Issues
Posted
Greetings,
I'm working on a JavaScript project in which I need to transform texts supplied by the user to floating-point values. However, throughout the conversion, I noticed an accuracy issue that generated unexpected results.
function convertToFloat(input) {
return parseFloat(input);
}
let userInput = "0.1";
let result = convertToFloat(userInput);
console.log("User input:", userInput);
console.log("Converted result:", result);
Here's an example of my code:
User input: 0.1
Converted result: 0.1
In principle, the result should be 0.1, but I'm receiving the following:
The conversion does not appear to preserve the correct floating-point representation, thus I went on the internet and read scaler article. I've heard about floating-point accuracy problems with JavaScript, but I'm not sure how to deal with them in this situation.
Could you share some best practices for dealing with accuracy issues during string-to-floating-point conversions? Your cooperation would be much appreciated.
Thank you for your time and knowledge.
Cancel
Post
Thank you
Replied
Wth
Why create a function that just calls another function??!?!??!
Cancel
Post
https://cdn.discordapp.com/attachments/974368060796440668/1091644029927686184/Siggy.png
Facts about me:
I skid :DD :D
Replied
i didnt really understand the issue but it seems pretty accurate to me:
User input: 0.0543953
Converted result: 0.0543953
Cancel
Post
https://cdn.discordapp.com/attachments/978212409145708565/1119225665649115167/WRD_Siggy.png
"Your code looks like a decompiled roblox script" - Me
Users viewing this thread:
( Members: 0, Guests: 1, Total: 1 )
Comments
SeizureSalad 40 Reputation
Commented
do 0.1 + 0.2 and then come back lmfao
0
Whoman 21 Reputation
Commented
@SeizureSalad that happens with every language, and i didnt see that in this post
0
SeizureSalad 40 Reputation
Commented
@Whoman nuh uh doens't hpapen in c#
0
Spanksterria 46 Reputation
Commented
0.1 + 0.2
Result: 0.30000000
Works on BasicCalculator just fine lmao
Download: https://github.com/Fish-Sticks/BasicCalculator/latest
Source (in BasicCalculator folder): https://github.com/Fish-Sticks/BasicCalculator/tree/master
Written by me all from scratch don't forget to star!
@SeizureSalad
@Whoman
@DracoFAAD
0