-5

I'm using float to display decimal numbers, but sometimes it doesn't display correct result.

For example, for 6.2/1000 the result is 0.0061999997.

I know why is this happening, but I wonder is there a way to display correct result, in this case, 0.0062?

EDIT: How to round a number to n decimal places in Java does not answer to my question, so why did you marked my question as already been answered in other place?

Numbers I wrote are only example. In the app user can enter any number and divide / multiply number with any other number, so the result maybe won't have any decimal points, maybe it will have 4 decimals, maybe it will have 7 decimals,...

2 Answers2

7

First, you need to understand that this isn't just a display issue - if you want to avoid displaying incorrect values, it helps to have the right values to start with.

You should use BigDecimal instead of float. That stores the value as an integer scaled by a factor of 10exp rather than the 2exp used by double and float.

If the BigDecimal.toString doesn't format the result the way you want, use DecimalFormat to perform the formatting instead.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
0

Format the decimal places use this:

DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(decimalPlace);
        String formatedValue = df.format(value);

Hope this will resolve your query.

jitain sharma
  • 542
  • 5
  • 19