Parse decimal real number to f64 without error

Hello i'm seeking for a way to store a string representation of a number. What i want is that if the number can be stored into a f64 without any data loss, use a f64 instead, e.g.

enum F64OrStr {
    F64(f64),
    Str(String),
}

There is actually parsing code in libcore, i know, but the existing code simply ignores non-significant errors, and there's no way to detect it. I can accept slower parsing, in exchange for always precise results, if out of range, just use the string variant.

Do you have any suggestions?

How strict are you about any data loss? Because e.g. "0.1" is impossible to represent in f64.

If storing a string is an option, maybe always just use the string?

Within std there's probably not much you can do. You could try if parsed_f64.to_string() == input_string, but this will give false negatives on slightly unusual notations.

1 Like

If you sometimes store things as strings that didn't necessarily need to be, is that ok? If so, you could use a simple heuristic like "14 sigfigs fit in an f64 for reasonable exponents".

2 Likes

Thank you for the suggestions, now i'm thinking about always using decimal64, maybe f64 just doesn't worth all these trouble...

I'll take a try to see if decimal*'s performance is good enough.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.