How to format double in java

How to format Double with dot?

How do I format a Double with String.format to String with a dot between the integer and decimal part?

String s = String.format("%.2f", price); 

3 Answers 3

String.format(String, Object . ) is using your JVM’s default locale. You can use whatever locale using String.format(Locale, String, Object . ) or java.util.Formatter directly.

String s = String.format(Locale.US, "%.2f", price); 
String s = new Formatter(Locale.US).format("%.2f", price); 
// do this at application startup, e.g. in your main() method Locale.setDefault(Locale.US); // now you can use String.format(..) as you did before String s = String.format("%.2f", price); 
// set locale using system properties at JVM startup java -Duser.language=en -Duser.region=US . 

Note that the 2nd approach (Formatter.format) returns the Formatter itself. One needs to instantize the Formatter with a object where to put the output to for it to work (docs.oracle.com/javase/8/docs/api/java/util/…)

Based on this post you can do it like this and it works for me on Android 7.0

import java.text.DecimalFormat import java.text.DecimalFormatSymbols DecimalFormat df = new DecimalFormat("#,##0.00"); df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ITALY)); System.out.println(df.format(yourNumber)); //will output 123.456,78 

This way you have dot and comma based on your Locale

Answer edited and fixed thanks to Kevin van Mierlo comment

Источник

Formatting Numeric Print Output

Earlier you saw the use of the print and println methods for printing strings to standard output ( System.out ). Since all numbers can be converted to strings (as you will see later in this lesson), you can use these methods to print out an arbitrary mixture of strings and numbers. The Java programming language has other methods, however, that allow you to exercise much more control over your print output when numbers are included.

Читайте также:  Java char string null

The printf and format Methods

The java.io package includes a PrintStream class that has two formatting methods that you can use to replace print and println . These methods, format and printf , are equivalent to one another. The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods on System.out . Thus, you can use format or printf anywhere in your code where you have previously been using print or println . For example,

The syntax for these two java.io.PrintStream methods is the same:

public PrintStream format(String format, Object. args)

where format is a string that specifies the formatting to be used and args is a list of the variables to be printed using that formatting. A simple example would be

System.out.format("The value of " + "the float variable is " + "%f, while the value of the " + "integer variable is %d, " + "and the string is %s", floatVar, intVar, stringVar);

The first parameter, format , is a format string specifying how the objects in the second parameter, args , are to be formatted. The format string contains plain text as well as format specifiers, which are special characters that format the arguments of Object. args . (The notation Object. args is called varargs, which means that the number of arguments may vary.)

Format specifiers begin with a percent sign (%) and end with a converter. The converter is a character indicating the type of argument to be formatted. In between the percent sign (%) and the converter you can have optional flags and specifiers. There are many converters, flags, and specifiers, which are documented in java.util.Formatter

int i = 461012; System.out.format("The value of i is: %d%n", i);

The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character. The output is:

The printf and format methods are overloaded. Each has a version with the following syntax:

public PrintStream format(Locale l, String format, Object. args)

To print numbers in the French system (where a comma is used in place of the decimal place in the English representation of floating point numbers), for example, you would use:

System.out.format(Locale.FRANCE, "The value of the float " + "variable is %f, while the " + "value of the integer variable " + "is %d, and the string is %s%n", floatVar, intVar, stringVar);

An Example

The following table lists some of the converters and flags that are used in the sample program, TestFormat.java , that follows the table.

Converters and Flags Used in TestFormat.java

Converter Flag Explanation
d A decimal integer.
f A float.
n A new line character appropriate to the platform running the application. You should always use %n , rather than \n .
tB A date & time conversion—locale-specific full name of month.
td, te A date & time conversion—2-digit day of month. td has leading zeroes as needed, te does not.
ty, tY A date & time conversion—ty = 2-digit year, tY = 4-digit year.
tl A date & time conversion—hour in 12-hour clock.
tM A date & time conversion—minutes in 2 digits, with leading zeroes as necessary.
tp A date & time conversion—locale-specific am/pm (lower case).
tm A date & time conversion—months in 2 digits, with leading zeroes as necessary.
tD A date & time conversion—date as %tm%td%ty
08 Eight characters in width, with leading zeroes as necessary.
+ Includes sign, whether positive or negative.
, Includes locale-specific grouping characters.
Left-justified..
.3 Three places after decimal point.
10.3 Ten characters in width, right justified, with three places after decimal point.

The following program shows some of the formatting that you can do with format . The output is shown within double quotes in the embedded comment:

import java.util.Calendar; import java.util.Locale; public class TestFormat < public static void main(String[] args) < long n = 461012; System.out.format("%d%n", n); // -->"461012" System.out.format("%08d%n", n); // --> "00461012" System.out.format("%+8d%n", n); // --> " +461012" System.out.format("%,8d%n", n); // --> " 461,012" System.out.format("%+,8d%n%n", n); // --> "+461,012" double pi = Math.PI; System.out.format("%f%n", pi); // --> "3.141593" System.out.format("%.3f%n", pi); // --> "3.142" System.out.format("%10.3f%n", pi); // --> " 3.142" System.out.format("%-10.3f%n", pi); // --> "3.142" System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi); // --> "3,1416" Calendar c = Calendar.getInstance(); System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2006" System.out.format("%tl:%tM %tp%n", c, c, c); // --> "2:34 am" System.out.format("%tD%n", c); // --> "05/29/06" > >

Note: The discussion in this section covers just the basics of the format and printf methods. Further detail can be found in the Basic I/O section of the Essential trail, in the «Formatting» page.
Using String.format to create strings is covered in Strings.

The DecimalFormat Class

You can use the java.text.DecimalFormat class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator. DecimalFormat offers a great deal of flexibility in the formatting of numbers, but it can make your code more complex.

The example that follows creates a DecimalFormat object, myFormatter , by passing a pattern string to the DecimalFormat constructor. The format() method, which DecimalFormat inherits from NumberFormat , is then invoked by myFormatter —it accepts a double value as an argument and returns the formatted number in a string:

Here is a sample program that illustrates the use of DecimalFormat :

import java.text.*; public class DecimalFormatDemo < static public void customFormat(String pattern, double value ) < DecimalFormat myFormatter = new DecimalFormat(pattern); String output = myFormatter.format(value); System.out.println(value + " " + pattern + " " + output); >static public void main(String[] args) < customFormat("###,###.###", 123456.789); customFormat("###.##", 123456.789); customFormat("000000.000", 123.78); customFormat("$###,###.###", 12345.67); >>
123456.789 ###,###.### 123,456.789 123456.789 ###.## 123456.79 123.78 000000.000 000123.780 12345.67 $###,###.### $12,345.67

The following table explains each line of output.

DecimalFormat.java Output

Value Pattern Output Explanation
123456.789 ###,###.### 123,456.789 The pound sign (#) denotes a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator.
123456.789 ###.## 123456.79 The value has three digits to the right of the decimal point, but the pattern has only two. The format method handles this by rounding up.
123.78 000000.000 000123.780 The pattern specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#).
12345.67 $###,###.### $12,345.67 The first character in the pattern is the dollar sign ($). Note that it immediately precedes the leftmost digit in the formatted output .

Источник

String.format() to format double in Java

Yes, Matt is right. %1, %2 and so on can be used to re-order the output based on the index of your input arguments. See this. You can omit the index and the default order will be assumed by the formatter.

It means that we need total 4 digits in ans , of which 3 should be after decimal . And f is the format specifier of double . x means the variable for which we want to find it . Worked for me . . .

I think it means it will be the fourth variable in the arguments which follow and have 3 places after the decimal.

@MichaelFulton It’s not that easy: String.format(«%014.3f» , 58.656565) -> 0000000058,657 : 14 symbols in total: 8 zeroes and 5 numbers and 1 comma. So in this case number 14 means the total number of symbols (extra ones get replaced with leading zero, could go without, then it would replace with space) in the result string. The .3 part is completely independent here.

However here: String.format(«%014.3f» , 58.656565) -> 58,657 . I take it because the preference goes to the .3f part: it first prints the number with 3 decimal places and after if there are symbols left it prints leading spaces (or zeroes/whatever). In this case the number is 2 + 3 + 1 = 6 symbols and we only wanted to print 4, so there are certainly no extra spaces.

@parsecer you posted the same String.format(«%014.3f» , 58.656565) two times, but the result is different, am I missing something?

If you want to format it with manually set symbols, use this:

DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); decimalFormatSymbols.setDecimalSeparator('.'); decimalFormatSymbols.setGroupingSeparator(','); DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", decimalFormatSymbols); System.out.println(decimalFormat.format(1237516.2548)); //1,237,516.25 

Locale-based formatting is preferred, though.

Useful answer! However, the last sentence «Locale-based formatting is preferred, though» does not make sense without context. There are pretty good use cases where you should NOT use locale-based formatting, when you want to generate a specific format of the String. E.g. you are implementing export of your data to an external file and you want to have full control over the format, not dependent on the current (or any) locale.

Double amount = new Double(345987.246); NumberFormat numberFormatter; String amountOut; numberFormatter = NumberFormat.getNumberInstance(currentLocale); amountOut = numberFormatter.format(amount); System.out.println(amountOut + " " + currentLocale.toString()); 

The output from this example shows how the format of the same number varies with Locale:

345 987,246 fr_FR 345.987,246 de_DE 345,987.246 en_US 

3 (3) +3 00003
Default floating-point format: 1234567,123000
Floating-point with commas: 1.234.567,123000
Negative floating-point default: -1.234.567,123000
Negative floating-point option: (1.234.567,123000)

Line-up positive and negative values:
1.234.567,12
-1.234.567,12

There are many way you can do this. Those are given bellow:

Suppose your original number is given bellow: double number = 2354548.235;

Using NumberFormat and Rounding mode

NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH); DecimalFormat decimalFormatter = (DecimalFormat) nf; decimalFormatter.applyPattern("#,###,###.##"); decimalFormatter.setRoundingMode(RoundingMode.CEILING); String fString = decimalFormatter.format(number); System.out.println(fString); 

Using String formatter

System.out.println(String.format("%1$,.2f", number)); 

In all cases the output will be: 2354548.24

During rounding you can add RoundingMode in your formatter. Here are some Rounding mode given bellow:

 decimalFormat.setRoundingMode(RoundingMode.CEILING); decimalFormat.setRoundingMode(RoundingMode.FLOOR); decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN); decimalFormat.setRoundingMode(RoundingMode.HALF_UP); decimalFormat.setRoundingMode(RoundingMode.UP); 

Here are the imports:

import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; 

Источник

Оцените статью