In Ruby, 0.0 * -1 == -0.0
.
I have an application where I multiply a bunch of Float
objects with -1
, but I don't like the -0.0
in the output, since it's confusing.
Is there a smart way of making Float#to_s
output 0.0
instead of -0.0
?
I'm completely fine with running every Float
object through some kind of scrubber/helper method, but the following just tends to make me even more confused:
def clean_output(amount)
if amount.zero?
0.0
else
amount
end
end
UPDATE:
To be more precise on what I'm looking for, I want a solution that I can run on a whole bunch of floats, some of which will be negative, some positive. The negative ones should remain negative unless they're negative zeroes, i.e. -0.0
.
Examples:
clean_output(-0.0) #=> 0.0
clean_output(-3.0) #=> -3.0
clean_output(3.0) #=> 3.0
There is actually a solution which does not require a condition.
def clean_output(value)
value + 0
end
output:
> clean_output(3.0)
=> 3.0
> clean_output(-3.0)
=> -3.0
> clean_output(-0.0)
=> 0.0
I don't actually like this solution better than the one I accepted, because of lack of clarity. If I'd see this in a piece of code I didn't write myself, I'd wonder why you'd want to add zero to everything.
It does solve the problem though, so I thought I'd share it here anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With