String.format() to format double in Java
String.format("%1$,.2f", myDouble);
String.format
automatically uses the default locale.
How do I format a double into a string (with only two decimal places)?
Use this code
fluidPerHourResultLabel.setText(new DecimalFormat("##.##").format(fluidHourInt));
Please check the link
Show only two digit after decimal
Double number formatting in java
This seems to be close to what you're asking for:
static String format(double n) {
if(Double.isInfinite(n) || Double.isNaN(n))
return Double.toString(n);
String result = BigDecimal.valueOf(n).toPlainString();
if(result.length() > 15)
result = String.format("%.15e", n);
return result;
}
Since your requirement is that the decimal places aren't fixed, I don't really see a way to do it with a formatter exclusively.
If you want a particular number of digits for the scientific notation, then you can use a format like "%.15e"
where 15
is the number of decimal digits you want.
Or possibly you want something like:
if(result.length() > 15)
result = new DecimalFormat("0.###############E0").format(n);
But if you're trying to "block align" to some maximum, then things get complicated because the number of fractional digits depends on the number of digits in the exponent.
Android: String format with Double value
%.0f is the format string for a float, with 0 decimal places.
The values you're passing to String.format are String, String when it needs to be Double, Double.
You do not need to convert the doubles to strings.
String headerText = String.format("%.0f kg / %.0f lbs", dWeightInKg, dWeightInLbs);
How can i format Double value comma separtely
System.out.println(String.format("%1$,.0f", amount));
OR
String formatAmount = new DecimalFormat("#,###,###,###,###").format(amount);
OR - Java 8
NumberFormat numberFormatter = NumberFormat.getNumberInstance(Locale.ENGLISH);
String formatAmount = numberFormatter.format(amount);
Double with specific format and two decimals
You don't want to combine NumberFormat
and String.format()
.
You can further configure your NumberFormat
object to tell it to use two decimal places:
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH);
numberFormat.setMinimumFractionDigits(2);
assertThat(numberFormat.format(1007.2), is("1 007,20"));
(and possibly setMaximumFractionDigits()
etc., depending on your needs -- see the Javadoc)
Take care - NumberFormat.format()
is not thread-safe.
Alternatively you can use String.format(locale, format, args)
:
assertThat(String.format(Locale.CANADA_FRENCH, "%,.2f", 1007.2), is("1 007,20"));
The ,
flag in the format tells the formatter to use a thousands-separator, and the locale tells it that the separator is a space.
String Format double to 00,00 - Java
Formatter class (which is the basis of String.format
method) operates using the concept of "fields". That is, each field is of some specific size and can be padded. In your case, you could use a formating like %05.2f
, which would mean a field of size 5, with 2 symbols after the point padded with zeroes to the left.
However, if you need some fine-grained formatting of numbers usually what you are looking for is DecimalFormat class, which allows you to easily customize how the numbers are represented.
Example (ideone link):
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
DecimalFormat decimalFormat = new DecimalFormat("#00.00");
System.out.println(decimalFormat.format(0.99f));
System.out.println(decimalFormat.format(9.99f));
System.out.println(decimalFormat.format(19.99f));
System.out.println(decimalFormat.format(119.99f));
}
}
Output:
00.99
09.99
19.99
119.99
why String.format 0.1d double value as exact 0.1 in java?
The Java specification requires this imperfect display of values. The f
format produces only as many significant digits as the Double.toString(double)
method would produce and then mindlessy appends zeros to get to the requested precision.
Per the documentation, for the f
format, if the precision exceeds the number of digits after the decimal point that Double.toString(double)
would produce, then “zeros may be appended to reach the precision.” This does not state what those zeros are appended to. Presumably, they are appended to the string that Double.toString(double)
would produce.
The documentation for Double.toString(double)
says it produces “as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double
.” I discuss that further here. For 0.1000000000000000055511151231257827021181583404541015625, Double.toString(double)
produces “0.1”. (The neighboring values, 0.09999999999999999167332731531132594682276248931884765625 and
0.10000000000000001942890293094023945741355419158935546875, are both further from .1 than 0.1000000000000000055511151231257827021181583404541015625 is, and they are formatted as “0.09999999999999999” and “0.10000000000000002”, so “0.1” serves to uniquely distinguish 0.1000000000000000055511151231257827021181583404541015625 from its neighbors.)
Thus, System.out.println(String.format("double 0.1= %.30f", d))
starts with the “0.1” from Double.toString(double)
and appends 29 zeroes.
Similarly, if you change d
to 0.09999999999999999167332731531132594682276248931884765625, String.format
produces “0.099999999999999990000000000000”—it has taken the toString
result and appended zeros. And for 0.10000000000000001942890293094023945741355419158935546875 it produces “ 0.100000000000000020000000000000”.
This conforms to the specification. The specified behavior is incapable of presenting the true value correctly, so I regard the specification as defective.
Incidentally, the Java specification is troublesome whether the requested precision is greater than or less than the number of digits that Double.toString(double)
would produce. In the case when the request permission is less, the Java specification requires a double rounding that can increase errors.
Best way to Format a Double value to 2 Decimal places
No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00"
, meaning exactly two decimal places.
If you use "#.##"
(#
means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d);
prints just "3"
, not "3.00"
.
Related Topics
Calling Super Super Class Method
Registering Multiple Keystores in Jvm
How to Execute Windows Commands Using Java - Change Network Settings
What Is the Regex for "Any Positive Integer, Excluding 0"
Priorityqueue Not Sorting on Add
How and Where to Use Static Modifier in Java
How to Set a Jlabel's Background Color
Jackson Overcoming Underscores in Favor of Camel-Case
Why Isn't This Code Causing a Concurrentmodificationexception
Generic Wildcard Types Should Not Be Used in Return Parameters
Is This the Best Way to Rewrite the Content of a File in Java
Maven: How to Change Path to Target Directory from Command Line
When Are Java Strings Interned
Firestore Query Documents Startswith a String