MindSwipe
MindSwipe

Reputation: 7910

How can I turn a integral and a fractional part back into a f32?

So I have a number, say 4.2, I can extract the integral and fractional parts like so:

let value = 4.3;
let integral = f32::trunc(value);
let fractional = get_frac(value); // returns '3'

This returns the correct things, but how can I turn this back into a f32? I'm storing these as integers and then only at a later date need to convert them back into a float.

Here is how I'm doing the conversion

Upvotes: 0

Views: 1050

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601909

Your function get_frac() inherently can't be inverted, since it maps different fractional parts to the same integer value. For both 4.2 and 4.02, the return value of get_frac() is 2. There is no way to tell from just the result which original value you started with.

A better approach would be to decide how many digits you want to include in your integer representation of your floating point number. If you want to include, say, four decimal digits, simply multiply your number by 10,000 and round to an integer. This operation can be approximately inverted by dividing by 10,000 again.

Upvotes: 7

Netwave
Netwave

Reputation: 42716

Maybe not the best way, but working, would be to transform to string, then parse it:

let res: f32 = format!("{}.{}", integral, fraction).parse().unwrap();

Playground

Upvotes: 1

Related Questions