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 ツ
  • 47,427
  • 17
  • 69
  • 97
georgeliatsos
  • 1,168
  • 3
  • 15
  • 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 ツ
  • 47,427
  • 17
  • 69
  • 97
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
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
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,074
  • 1
  • 10
  • 19