1

I know that in ruby you can use printf to format a number to be printed with a certain amount of decimal places, ie. 1.2 --> 1.20, etc. What I would like to know is how it's possible to assign a number with certain decimal places to a variable to be able to use later. I need to use more precise numbers in my calculations and can't find anywhere that explains how to do that. I have looked at this answer here but it looks like that is for a specific version of rails, and I am using Ruby alone. I have tried playing around a little with the number_to_precision a little but am very new to Ruby and still don't really understand how to implement it. Is it possible to do this?

Community
  • 1
  • 1
Luminusss
  • 571
  • 1
  • 6
  • 27

2 Answers2

2

The method number_with_precision is a helper method for views only, and it returns a string version of the number. It doesn't return a number with the specified precision, if that's what you're looking for. The good news is, if you want exactly what number_with_precision gives you, you can use sprintf.

sprintf('%.2f', 3.1415926)    # result: "3.14"

sprintf returns a value you can store, instead of printing to stdout like printf does. So you can easily capture it:

number = sprintf('%.2f', 3.1415926)

If you wanted to treat it as a number, you could probably build a class that does this for you, and converts to and from a Float as needed.

Jaime Bellmyer
  • 23,051
  • 7
  • 53
  • 50
  • so then in this case does it save it as a string? which would then need to be converted to a float – Luminusss Oct 05 '14 at 17:09
  • that works perfect, exactly what I was looking for, thank you! I did not know you could use that to save a variable. – Luminusss Oct 05 '14 at 17:18
  • 1
    Yes, but this is also true of number_with_precision in Rails. You could then call `.to_f` on the number to get a float, and store that instead of the string if you want, but you would lose any trailing zeros. – Jaime Bellmyer Oct 05 '14 at 17:20
1

To get arbitrary floating point precision numbers in Ruby you use BigDecimal objects to perform your calculations.

This class guarantees your calculations will use as many digits after the dot as necessary and it will not be plagued by the rounding errors caused by transforming base 10 to base 2 numbers.

Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158