We help IT Professionals succeed at work.
Get Started

Convert Float to Integer in Groovy gives rounding errors

Steve Wales
Steve Wales asked
on
1,953 Views
Last Modified: 2015-03-04
I am having to grab some data from an Oracle database via Groovy script and dump it into a flat file to upload to a bank for EFT payments.

The data is stored in the database as NUMBER(15,2) - it represents a dollar value.

The bank expects the number to be written out as a string, without the decimal.

My thought was to read the value from the database ($528.10) and store it in a float - which seems to work.

In order to output the value as 0000052810 (value is 10 characters, assuming 8 digits for dollars and last 2 digits for cents) I thought I'd try this.

Float x1
x1 = 528.1
x2 = x1 * 100

Open in new window


However multiplying the float by 100 is giving me rounding errors.  

I added output of the two values:

println x1.toString()
println x2.toString()

Which gave me:

528.1
52809.99755859375

I could add: x3 = x2.round() to make the output 52810 - but since I'm dealing with financial information here, I'd rather get an exact conversion than rely on rounding.  Anyone able to offer me a clean solution to this ?
Comment
Watch Question
Senior Database Administrator
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 6 Answers and 8 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE