The question is how I can do to truncate a float number ending in 0.

I have an exercise where I truncate a float number to 2 decimals, the
problem is that if the decimal ends in 0 instead of return the full
number, only returns the first number.

For example:

53454545.5459332345 >>> 53454545.54 is OK.

Now, this number:

948484747.5000000 >>> 948484747.5 is incorrect because it should be
948484747.50

To truncate the number to 2 decimals I’m using this code:

###################################

(number*100).to_i / 100.0

##################################

which works correctly if the truncated decimal number does not end in 0.

this is a big misunderstanding of numbers. You mistake the representation of a number for the number itself. 948484747.5000000,
948484747.50 and 948484747.5 are all the exact same number. So trying to
“convert” one to another makes absolutely no sense.

The only difference is how the number is written down. So what you’re
actually looking for is not a number operation but a specific way of
converting a number to a string. You want the decimal representation of
the number with exactly two decimal places. And Wybo showed you the
typical way of doing this.

2659876.77 is correct. This is how numbers ‘work’. There is either a
fundamental mis-understanding of numbers or you really want strings.

Have you ever heard of truncating?

When a number is “rounded” differently from what we know from school
(which is commercial rounding) doesn’t mean it is “wrong”. You can round
any way you like.

When a number is “rounded” differently from what we know from school
(which is commercial rounding) doesn’t mean it is “wrong”. You can round
any way you like.

this is a big misunderstanding of numbers. You mistake the representation of a number for the number itself. 948484747.5000000,
948484747.50 and 948484747.5 are all the exact same number. So trying to
“convert” one to another makes absolutely no sense.

I couldn’t agree more. Usually formatting should only be applied on
output (i.e. presentation to the user, printf comes to mind). Before
that rounding should be avoided to keep calculations as precise as
possible.

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.