3

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?

ΦXocę 웃 Пepeúpa ツ
  • 45,713
  • 17
  • 64
  • 91
georgeliatsos
  • 1,099
  • 2
  • 14
  • 34

3 Answers3

3

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);
ΦXocę 웃 Пepeúpa ツ
  • 45,713
  • 17
  • 64
  • 91
2

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
Deadpool
  • 33,221
  • 11
  • 51
  • 91
1

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

Imbar M.
  • 1,014
  • 1
  • 10
  • 19