I want to convert number 2.55 to 255 in java.
I have tried the following code but I am getting 254 instead of 255:
final Double tmp = 2.55;
final Double d = tmp * 100;
final Integer i = d.intValue();
What is the correct way to achieve this?
I want to convert number 2.55 to 255 in java.
I have tried the following code but I am getting 254 instead of 255:
final Double tmp = 2.55;
final Double d = tmp * 100;
final Integer i = d.intValue();
What is the correct way to achieve this?
you have to round that value, and you can use primitives for that.. i.e. use the primitive double instead of the wrapper class Double
final double tmp = 2.55;
final double d = tmp * 100;
long i = Math.round(d);
System.out.println("round: "+ i);
It is simple by using BigDecimal
BigDecimal bg1 = new BigDecimal("123.23");
BigDecimal bg2 = new BigDecimal("12323");
bg1= bg1.movePointLeft(-2); // 3 points right
bg2= bg2.movePointLeft(3); // 3 points left
System.out.println(bg1); //12323
System.out.println(bg2); //12.323
the value of d is 254.999999999997. this is a problem with floating point calculations. you could use
i = Math.round(d);
to get 255.
--- delete the bottom.. was wrong