0

I have to write a program with the following requirements:

  1. I have a variable of type float, say float a = 3333.333f;

  2. I have a variable of type int, say int b = 9999;

When I perform a*b in calculator, the result will be 33329996.667

After rounding up the decimals to 2 places, I want to print the value as 33329996.67 in java. I tried with long, double, float, big decimal, But couldnt succeed.

Can anyone please help me solving this?

user1493004
  • 101
  • 2
  • 2
  • 6

2 Answers2

2

float only has 7 digits of precision, so its not a good choice for a result with more than 7 digits. double has up to 16 digits of accuracy and is a better choice.

double a = 3333.333;
int b = 9999;
System.out.printf("%.2f", a * b);

prints

33329996.67
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

To determine the number of digits after the comma you have to apply a little trick:

First shift the comma to the right for the amount of digits you want to have, then cut the whole number e.g. with Math.ceil(float f) and then shift the comma back to the left.

That will illustrate that:

float f = 33329996.667;

float f2 = Math.ceil((f * 100)) / 100;

f2 now has the value 33329996.67.

Hope this helps.

EDIT: For formatting have a look here

Community
  • 1
  • 1
marc wellman
  • 5,808
  • 5
  • 32
  • 59
  • Thanks Marc for yur answer. But I have one doubt. When I do Sysout for 33329996.66, it displays as 3.3329996E7. How to print as 33329996.66 – user1493004 Jun 30 '12 at 13:09
  • 3
    This technique does not work in over 90% of cases. It can't. Floating-point values don't have decimal places to truncate, they have binary place. If you want decimal places you have to use a decimal radix. – user207421 Jun 30 '12 at 13:20
  • I would use `round` instead of `ceil` – Peter Lawrey Jun 30 '12 at 13:26
  • @PeterLawrey I would use a decimal radix via BigDecimal or DecimalFormat. At least it will do what is required. Nothing in Math will. – user207421 Jun 30 '12 at 13:28
  • @PeterLawrey well you're right Math.round(double d) decides on its own whether to round up or down but I think i depends on the requirements :) – marc wellman Jun 30 '12 at 13:32
  • It doesn't depend on the requirements. The problem is that `float` and `double` don't care about decimal places, they only care about binary places. You _must_ use `BigDecimal` or `DecimalFormat` to deal with a number of decimal places. – Louis Wasserman Jun 30 '12 at 14:02
  • BigDecimal is the best solution for the most predictable behaviour. Most financial houses and trading system however use `double` (dollars) or `int` or `long` (cents) What might be the best in theory is rarely needed in practice. – Peter Lawrey Jun 30 '12 at 20:05