0

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?

1
  • 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? Commented Mar 22, 2017 at 19:58

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So, the answer is NO :)
@Ilya The answer is "YES, BUT".
I think the question is about converting a string to float with double zero in the end.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.