I would like the following values.
10.0 → 10
1.5 → 1.5
In the following process, the value=1 instead of value=1.0, but
Is there a better way?
value = 10.0/10 (some calculation)
if value==value.to_i
value=value.to_i
end
As the comment says, "Calculation is done in floating-point type, and if the calculation results can be expressed in integers, I want to erase the decimal "0" or eventually make it a string type," you should format it when viewing or converting to a string.
irb(main): 008:0>value=10.0/10
= > 1.0
irb(main): 009:0>str_value = "%.15g" %value
= > "1"
irb(main): 010:0>print(str_value)
1 = > nil
irb(main): 011:0>
The execution example is from irb, so the value of the => expression
is unnecessary, but you can see that the value of the string type str_value
does not include .0
.
If you use to_s
to string in the default format, it often doesn't work out the desired string, but in that case, it's better to specify the format immediately without thinking about fiddling with the value as it is.
How about using ActiveSupport
?
require "active_support"
require "active_support/number_helper"
ActiveSupport:: NumberHelper.number_to_rounded (1.0, strip_insignificant_zero: true)
# = > "1"
ActiveSupport:: NumberHelper.number_to_rounded (1.5, strip_insignificant_zero: true)
# = > "1.5"
https://www.rubydoc.info/docs/rails/4.0.0/ActiveSupport%2FNumberHelper:number_to_rounded
© 2024 OneMinuteCode. All rights reserved.