Is there any worthy Ruby method to count the number of digits in a float? Also, how do I specify the precise when to_s float numbers?
Asked
Active
Viewed 7,012 times
4
-
5Keep in mind that the full number of digits in a float's decimal representation is not necessarily a useful number to have. For example, 0.1 is cannot be precisely represented in binary, so you might not be particularly happy to discover that 0.1 has 18 digits without rounding. – Chuck Oct 02 '09 at 21:11
3 Answers
6
# Number of digits
12345.23.to_s.split("").size -1 #=> 7
# The precious part
("." + 12345.23.to_s.split(".")[1]).to_f #=> .023
# I would rather used
# 12345.23 - 12345.23.to_i
# but this gives 0.22999999999563

khelll
- 23,590
- 15
- 91
- 109
-
4Your solution to count digits doesn't take into account the `'-'` on negative numbers. Also, what's your reasoning for doing `to_s.split("").size` instead of just doing `to_s.size`? – Pesto Oct 03 '09 at 12:48
2
to specify precision of a float in Ruby. you can use the round method.
number.round(2)
2 is the precision.
53.819.round(2) -> 53.82

Postscripter
- 521
- 7
- 18
-
like rails number_with_precision(precision: 3) just `"%.3f" % 53.82 => "53.820"` – YaEvan Feb 02 '21 at 07:29
1
I think you should check out the number_with_precision helper.
number_with_precision(13, :precision => 5) # => 13.00000

Mike Buckbee
- 6,793
- 2
- 33
- 36