Java examples for Language Basics:double
Use the DecimalFormat class to format and round the value to the precision.
import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; public class Main { public static void main(String[] args) { formatDouble(new Double("345.9372")); }//from w ww.j a v a2 s .com public static void formatDouble(double myDouble) { NumberFormat numberFormatter = new DecimalFormat("##.000"); String result = numberFormatter.format(myDouble); System.out.println(result); // Obtains an instance of NumberFormat class NumberFormat format = NumberFormat.getInstance(); // Format a double value for the current locale String result2 = format.format(83.404); System.out.println("Current Locale: " + result2); // Format a double value for an Italian locale result = NumberFormat.getInstance(Locale.ITALIAN).format(83.404); System.out.println("Italian Locale: " + result); // Parse a String into a Number try { Number num = format.parse("75"); System.out.println("Now a number: " + num); } catch (java.text.ParseException ex) { System.out.println(ex); } } }
DecimalFormat Pattern Characters
Character | Description |
---|---|
# | Digit; blank if no digit is present |
0 | Digit; zero if no digit is present |
. | Decimal |
- | Minus or negative sign |
, | Comma or grouping separator |
E | Scientific notation separator |
; | Positive and negative subpattern separator |