Ruby code to remove insignificant decimal places?
Asked Answered
C

2

5

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

Cavite answered 17/6, 2016 at 22:8 Comment(1)
Did you try this convert method? It works for the 4 cases you provided.Ardisardisj
O
15

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.

Obel answered 17/6, 2016 at 22:36 Comment(7)
if you pass it integer then it will also remove 0 from an integer value, so don't pass it integer values "20" => 2Gendarmerie
Since the point was to remove trailing zeroes from floating point then it shouldn't get passed an integer. It'd be an easy thing to protect against though.Obel
You need to remove the question mark from regex n.to_s.sub(/\.0+$/, '')Vaporous
This DOES NOT WORK strip_trailing_zero(250) => "25"Monzon
It did when the question was asked and answered. Ruby has changed.Obel
If you are working with rails, you may check the number_with_precision method from ActionView/Helpers/NumberHelperPhytosociology
@theTinMan: Ruby hasn't changed. The regex, /\.?0+$/ says "Maybe there's a ., maybe not, followed by one or more 0." Your replacement would turn "250" (Not a ., but one 0) into "25" in any language.Weekend
T
8

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"
Trinh answered 30/6, 2021 at 3:56 Comment(2)
0 comes to -0 with %gBerneta
Be careful! It looks like it works but if you pass 21385524.0031 You'll get: 2.13855e+07Monzon

© 2022 - 2024 — McMap. All rights reserved.