kitokid
kitokid

Reputation: 3117

setting decimal places to a float value

float a= (float) 1846.4;

NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);

float b = Float.parseFloat( df.format(a));

What would be the best way to set decimal places for a float (I just want to set 2 decimal places of a float value which can be 2013.43452 or 2392.2) ? Now I am getting exception like Exception in thread "main" java.lang.NumberFormatException: For input string: "1,846.40".

Upvotes: 0

Views: 11517

Answers (4)

user207421
user207421

Reputation: 310840

What would be the best way to set decimal places for a float

There isn't one. Floats don't have decimal places. They have binary places.

If you want decimal places you have to use a decimal radix, either a BigDecimal or the result of DecimalFormat.format().

Upvotes: 0

GregHNZ
GregHNZ

Reputation: 8969

Sounds like you simply want to round to two decimal places.

Number format and mucking around with strings isn't where you want to go.

Try this:

float b = Math.round(a * 100)/100.0f;

Upvotes: 1

Thomas
Thomas

Reputation: 88707

To get your formatting + parsing to work, just use df again:

float b = df.parse( df.format(a));

However, I still don't see any sense in that. You can't define the number of decimal places in a floating point number. 1846.40 is the same as 1846.4 or 1846.400, the trailing zeros are totally irrelevant.

Those digits come into play when you have output, e.g. writing the number to a string. But there are other facilities to do that, e.g. a string format pattern.

If you need to restrict the number of fraction digits internally use BigDecimal where you can set the scale and thus define the number of fraction digits it represents.

Upvotes: 1

Péter Török
Péter Török

Reputation: 116246

I think the direct problem causing the NFE is the thousand separators in the string, not the number of decimal places. You have both a ',' and a '.' in the string, and parseFloat doesn't like that.

Note, however, that you can't fix the number of decimal places in a float value - it is entirely a formatting issue. Specifically, trailing 0's have no significance in floating point values, thus will not be shown by default. You need to format the value according to your wishes at the point of output (when converting it into a displayable String e.g. by using DecimalFormat as you did above).

Upvotes: 3

Related Questions