Shailendra
Shailendra

Reputation: 367

Truncate Float value up to two decimal point in java

DecimalFormat hisFormat = new DecimalFormat("########.##");
hisFormat.setRoundingMode(RoundingMode.DOWN);

Float x=12345678.12345f;
System.out.println("Float Value " + hisFormat.format(x));

Above code print "Float Value" as 12345678 I need 12345678.12

How can I get my result? Please let me know.

Upvotes: 3

Views: 2117

Answers (1)

Haifeng Zhang
Haifeng Zhang

Reputation: 31903

Use Double other than Float, or you will lose precision

DecimalFormat hisFormat = new DecimalFormat("######.##");
hisFormat.setRoundingMode(RoundingMode.DOWN);
Double x = 12345678.12345;
System.out.println("Float Value " + hisFormat.format(x));

Use Float the result is 12345678

Use Double the result is 12345678.12

Upvotes: 1

Related Questions