-1

I have such code:

int number1 = 20;
int number2 = number1/100;

I want to get percentage of number1 as 0,2 -> I suppose int should be converted into some other type. But I need 0,2 to use for BigDecimal number. How can I get this 0,2 from int number1 = 20?

int number1 = 20 has to be in that type.

Will be grateful for help.

JeyKey
  • 413
  • 1
  • 9
  • 22

2 Answers2

2

Using a BigDecimal is appropriate here. You can use BigDecimal.valueOf in order to convert int to BigDecimal. Then, you can divide by specifying a scale and a rounding mode.

Example :

System.out.println(
BigDecimal.valueOf(20).divide(BigDecimal.valueOf(100), 1, RoundingMode.HALF_UP)
);

Will display :

0.2

With a different scale :

System.out.println(
BigDecimal.valueOf(20).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP)
);

It will display :

0.20

Or like stated in the question comments, you can also create directly the BigDecimal from a String :

System.out.println(new BigDecimal("0.2"));
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
0

Divide the int by a floatvalue to give to it a floating number representation and assign it to a floating number.

float number2 = number1/100F;
davidxxx
  • 125,838
  • 23
  • 214
  • 215