Count the number of decimal places

Hi All,

I am using Ruby 2.3 . I need to count the number of decimal places in a
float.

Like : 19.375 should return 3
-0.010 should return 3
81.10 should return 2

Can anyone let me know how i can do this?

Thanks

The display representation of trailing 0 is not inherently doable in a
Float itself so you never see something such as -0.010 in ruby.

You can quickly test this in irb by issuing:

-0.010 # => -0.01

So the last 0 was magically chopped away. (Well, it was never there to
begin with, so it was not really chopped away anyway, but you get the
point.)

If you have a String then this is trivial and I am not sure why you
state that it is a float since there can not be -0.010 floats. If you
have a String, there are lots of ways to calculate the amount of
characters past the ‘.’.

To name one:

x = "-0.010"; x[x.index('.')..-1].delete('.').size # => 3

I am sure there are many prettier and better ways too but admittedly I
have not thought about it much. :slight_smile:

Hi Rob,

you do know that,

Float(0.10) # => 0.1