Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby code to remove insignificant decimal places?

I would like to get an elegant code, which removes the insignificant closing zeroes, eg:

29.970 => 29.97
29.97 => 29.97
25.00 => 25
25.0 => 25

I tried:

argument.to_r.to_f.to_s

But doesn't work in every cases, eg on 25.00 gives 25.0

like image 491
Konstantin Avatar asked Aug 25 '26 01:08

Konstantin


2 Answers

Trailing zeros are only significant when the number is a string:

def strip_trailing_zero(n)
  n.to_s.sub(/\.0+$/, '')
end

strip_trailing_zero(29.970) # => "29.97"
strip_trailing_zero(29.97)  # => "29.97"
strip_trailing_zero(25.00)  # => "25"
strip_trailing_zero(25.0)   # => "25"
strip_trailing_zero(250)   # => "250"

This converts the incoming floating point numbers and converts them into a string, then uses a simple sub search and replace to trim the trailing 0 and optionally the decimal point.

You can figure out how to convert them back to integers and floats if that's necessary. This will remove significant trailing zeros if you pass a integer/fixnum. How to guard against that is also something for you to figure out.

like image 108
the Tin Man Avatar answered Aug 26 '26 14:08

the Tin Man


Try sprintf('%g', value_here) ?

`g` ->  Convert a floating point number using exponential form
  | if the exponent is less than -4 or greater than or
  | equal to the precision, or in dd.dddd form otherwise.

https://apidock.com/ruby/Kernel/sprintf

sprintf('%g',29.970) # => "29.97"
sprintf('%g',29.97)  # => "29.97"
sprintf('%g',25.00)  # => "25"
sprintf('%g',25.0)   # => "25"
like image 43
aldrien.h Avatar answered Aug 26 '26 15:08

aldrien.h



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!