Dave's Brain

Browse - Programming Tips - How can I format a number with two decimal places?

Date: 2013aug30
Language: Java

Q.  How can I format a number with two decimal places?
(eg dollars and cents)

A.  For floats:

String twoDecimal(final float f) { return new DecimalFormat("#.##").format(f); }
And for doubles its exactly the same:
String twoDecimal(final double d) { return new DecimalFormat("#.##").format(d); }
Example use:
void exampleUse() { System.out.println("value="+twoDecimal(45.123456)); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.