0

I am doing simple calculation in java. Expected result is 51.3348 but what I am getting is 51.0, here is my calculation

    float percent = (7819140000l-3805200000l)*100/7819140000l;

Is that problem with datatype? How can I resolve this to get value as 51.3348

Thanks in Advance

Karthi Krazz
  • 121
  • 1
  • 2
  • 9
  • 1
    It is being truncated because you are not using any floats in the equation. – Kelvin Sep 02 '16 at 06:35
  • even casting to float will work – Shahid Sep 02 '16 at 06:38
  • try this onepublic String format_Decimal(double decimalNumber) { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(5); nf.setMinimumFractionDigits(2); nf.setRoundingMode(RoundingMode.HALF_UP); String x = nf.format(decimalNumber); return x; }double percent=(7819140000l-3805200000l)*100f/7819140000l; – Chandu D Sep 02 '16 at 06:53
  • long Division Yields long result. to get float result either specify value as float by appending 'f' float percent = (7819140000l-3805200000l)*100f/7819140000l; or Explicitly cast it. float percent = (float)(7819140000l-3805200000l)*100f/7819140000l; – Rahul Sawant Sep 02 '16 at 06:54

1 Answers1

1

add an f to one of the values:

float percent = (7819140000l-3805200000l)*100f/7819140000l;

if yiu do not do it, Java will make a devision by long values

Jens
  • 67,715
  • 15
  • 98
  • 113
  • I would use a double instead of float, even though the OP only needs 6 digits of accuracy. This preserves half a tirllion times more precision – Peter Lawrey Sep 02 '16 at 07:07