Categories > Coding > Javascript >

Floating-Point Conversion Precision Issues

Posts: 13

Threads: 8

Joined: Mar, 2023

Reputation: 0

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.

  • 0

Thank you

Posts: 71

Threads: 6

Joined: Aug, 2022

Reputation: 6

Replied

Wth

Why create a function that just calls another function??!?!??!

  • 0

Posts: 1430

Threads: 71

Joined: May, 2022

Reputation: 20

Replied

i didnt really understand the issue but it seems pretty accurate to me:

User input: 0.0543953

Converted result: 0.0543953

Comments

SeizureSalad 40 Reputation

Commented

do 0.1 + 0.2 and then come back lmfao

  • 0

Whoman 20 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

  • 0

i use arch btw

Users viewing this thread:

( Members: 0, Guests: 2, Total: 2 )