I want to convert "5565.80" to 5565.80 and "5565.00" to 5565.00. The issue with to_f is that it removes the last 0 when the 2 decimals are .00. Is there a single way to do both?
-
Welcome to Stack Overflow. Please read "How to Ask" and "minimal reproducible example". Your question isn't a good fit for Stack Overflow. Where did you search, and what did you find and why didn't that help? Did you write code? If not, why? If so, where is the minimum code that demonstrates a specific problem you encountered?the Tin Man– the Tin Man2017-03-22 19:58:30 +00:00Commented Mar 22, 2017 at 19:58
2 Answers
Float
You can convert "5565.80" to a float :
value = "5565.80".to_f
# 5565.8
And then display the value with two decimals :
'%.2f' % value
# "5565.80"
A float has double-precision in Ruby, so your value will actually be :
5565.800000000000181898940354...
As a float, you cannot save exactly 5565.80.
Exact values
Integer
If you want exact values (e.g. for currency), you could use integers for cents :
"5565.80".delete('.').to_i
# 556580
When you need the corresponding float, you could divide it by 100.0.
Decimal
If you're working with a database, you could use decimal(20,2) or something equivalent.
BigDecimal
You could also use BigDecimal :
require 'bigdecimal'
BigDecimal.new("5565.80")
It will save the exact value but will be much slower than int or float.
3 Comments
You can use #round.
The argument to round is how many decimals you want to round to. Some examples:
5565.80.round(2) # => 5565.8 # omits trailing 0's
5565.00.round(2) # => 5565.0 # only keeps the decimal to show that this is a float
5565.79.round(2) # => 5565.79 # rounds to two digits
5565.123.round(3) # => 5565.123 # rounds to three decimal places, so nothing is lost
5565.123.round(2) # => 5565.12 # drops the 3
5565.129.round(2) # => 5565.13 # drops the 9 and rounds up