Kriton Georgiou
Kriton Georgiou

Reputation: 93

Convert double to int without loss of precision in java

I would like to convert a double (for example price with a value of 1.90) to an integer without losses! I am making a program that processes money, and I have to input them as doubles, and then convert them to integers so that I can proccess them and for example when I have 1.90 euros and i want to convert it to cents it will appear as 189 cents instead of 190! please help me :) thanks in advance

Upvotes: 0

Views: 5198

Answers (2)

Dariusz
Dariusz

Reputation: 22241

Check the details on how doubles and floats behave in java in the JLS

Well, you could round the value to desired precision. As long as you're within given format's precision (~15 digits for double ~7 for float) you'll get good results.

double fractValue = 1.90; // 1.8999999....
int val = (int)Math.round(fractValue*100);

It's much better idea to use BigDecimal though. You will never lose any precision then.

Upvotes: 5

Jaskaranbir Singh
Jaskaranbir Singh

Reputation: 2034

double x = 1.89; //Or whatever
String[] y = String.valueOf(x).split("[.]");  // Returns array having 1 and 89
String z = y[0] + y[1];  //String which is = 189
    if(y[1].length()==1)
        z +="0";  // Add a 0 in end if required
int finalInt = Integer.parseInt(z);  //Convert String to Integer

finalInt should be what you want.

Upvotes: -1

Related Questions