I\'m having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it\'s 4.00 instead?
With Java 8, you can use format
method..: -
System.out.format("%.2f", 4.0); // OR
System.out.printf("%.2f", 4.0);
f
is used for floating
point value..2
after decimal denotes, number of decimal places after .
For most Java versions, you can use DecimalFormat
: -
DecimalFormat formatter = new DecimalFormat("#0.00");
double d = 4.0;
System.out.println(formatter.format(d));
First import NumberFormat
. Then add this:
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
This will give you two decimal places and put a dollar sign if it's dealing with currency.
import java.text.NumberFormat;
public class Payroll
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
int hoursWorked = 80;
double hourlyPay = 15.52;
double grossPay = hoursWorked * hourlyPay;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));
}
}
Works 100%.
import java.text.DecimalFormat;
public class Formatting {
public static void main(String[] args) {
double value = 22.2323242434342;
// or value = Math.round(value*100) / 100.0;
System.out.println("this is before formatting: "+value);
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
}
}
You can do it as follows:
double d = 4.0;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
Using String.format, you can do this:
double price = 52000;
String.format("$%,.2f", price);
Notice the comma which makes this different from @Vincent's answer
Output:
$52,000.00
A good resource for formatting is the official java page on the subject
You can use any one of the below methods
If you are using java.text.DecimalFormat
DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance();
decimalFormat.setMinimumFractionDigits(2);
System.out.println(decimalFormat.format(4.0));
OR
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(4.0));
If you want to convert it into simple string format
System.out.println(String.format("%.2f", 4.0));
All the above code will print 4.00