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
Replied
i didnt really understand the issue but it seems pretty accurate to me:
User input: 0.0543953
Converted result: 0.0543953
Cancel
Post
Did I mention I use arch btw?
Users viewing this thread:
( Members: 0, Guests: 1, Total: 1 )
Comments
SeizureSalad 36 Reputation
Commented
do 0.1 + 0.2 and then come back lmfao
0
Whoman 17 Reputation
Commented
@SeizureSalad that happens with every language, and i didnt see that in this post
0
SeizureSalad 36 Reputation
Commented
@Whoman nuh uh doens't hpapen in c#
0