I'm going crazy! I've searched the java sites, and ran google searches, but can't figure out how to format a normal double variable to display just the first two decimals. I can get it to work with currency, but can't figure out how to do it normally. Help me please! I'm using an IDE Eclipse to write my program.
How do you format a number to 2 decimals in java?
import java.text.DecimalFormat;
...
DecimalFormat df = new DecimalFormat( "#########0.00");
String formattedValue = df.format(someDoubleValue);
Use ".00" if you always want to see two numbers past the decimal point. Use ".##" if you only want to see numbers if they're non-zero. For example "3.1" formated "0.00" is "3.10" but formatted "0.##" is "3.1".
Reply:Currently in the market, most of the monetary value would be stored in BigDecimal.
Example:
BigDecimal d = new BigDecimal(1.233);
System.out.println(" big d val %26gt; " + d);
System.out.println(" big d val in 2 decimal %26gt; " + d.setScale(2, BigDecimal.ROUND_UP));
- setScale 2 means 2 decimal points.
- BigDecimal.ROUND_UP is one of the option, u may choose to ROUND_DOWN, ROUND_FLOOR, etc
:) Since u are using eclipse, the rest should b easy for u
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment