Using Float For Currency

H

Hunter's Lists

Howdy,

I have some methods that manipulate floats that represent a currency amount.

I often end up with more precision than I need, i.e.: $9.756.

What is the best way to scale that to 9.76?

Cheers.
 
W

Wilson Bilkovich

Howdy,

I have some methods that manipulate floats that represent a currency amou= nt.

I often end up with more precision than I need, i.e.: $9.756.

What is the best way to scale that to 9.76?
Try:
val =3D 9.756
sprintf("%.2f", val)
That says "print 'val' as a floating point value, with two decimal
places of precision.
 
N

Neil Stevens

Hunter's Lists said:
Howdy,

I have some methods that manipulate floats that represent a currency amount.

I often end up with more precision than I need, i.e.: $9.756.

What is the best way to scale that to 9.76?

require 'bigdecimal'

amount = BigDecimal.new('9.756')
rounded = (amount * 100).round / 100
printf('%.02f', rounded)

Outputs '9.76'
 
D

Dave Burt

Wilson Bilkovich said:
val = 9.756
sprintf("%.2f", val)
That says "print 'val' as a floating point value, with two decimal
places of precision.

Or just
"%.2f" % val

Cheers,
Dave
 
E

Eero Saynatkari

Hunter's Lists said:
Howdy,

I have some methods that manipulate floats that represent a currency
amount.

I often end up with more precision than I need, i.e.: $9.756.

What is the best way to scale that to 9.76?

I think this has already been covered, but:

"Money does not float!"

:)


E
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,647
Latest member
NelleMacy9

Latest Threads

Top