210

How can I use String.format(format, args) to format a double like below?

2354548.235 -> 2,354,548.23

Ivar
  • 6,138
  • 12
  • 49
  • 61
kike
  • 2,105
  • 2
  • 13
  • 5

7 Answers7

332
String.format("%1$,.2f", myDouble);

String.format automatically uses the default locale.

David Tang
  • 92,262
  • 30
  • 167
  • 149
  • 39
    You can also use a specific locale by using `String.format(Locale.GERMAN, "%1$,.2f", myDouble);` – Olivier Grégoire Feb 03 '11 at 11:54
  • 13
    If there is more than one double to format, use %1, %2, and so on. For example String.format("%1$,.2f, %2$,.2f", myDouble, aDouble) – Moesio Mar 10 '13 at 05:29
  • 5
    I believe the "%1$" is optional in this case. Works for me with just "%,.2f" as the format String. – Matt Passell Mar 12 '14 at 19:36
  • 5
    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](https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html). You can omit the index and the default order will be assumed by the formatter. – praneetloke May 14 '16 at 16:06
  • 2
    You should give an explanation what the different parts mean. – Mitulát báti Mar 25 '19 at 21:37
50
String.format("%4.3f" , x) ;

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 . . .

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
user3304797
  • 509
  • 4
  • 4
  • 1
    I think it means it will be the fourth variable in the arguments which follow and have 3 places after the decimal. – Michael Fulton Jan 17 '17 at 19:51
  • @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. – parsecer Mar 05 '20 at 00:13
  • 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 Mar 05 '20 at 00:13
  • @parsecer you posted the same `String.format("%014.3f" , 58.656565)` two times, but the result is different, am I missing something? – RAM237 Mar 22 '21 at 13:28
  • @RAM237 Yeah there must have been the typo. But now I don't remember what it was about – parsecer Mar 22 '21 at 13:40
27

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.

mdrg
  • 3,242
  • 2
  • 22
  • 44
  • 4
    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. – Honza Zidek Feb 15 '16 at 10:21
22

code extracted from this link ;

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
Gursel Koca
  • 20,940
  • 2
  • 24
  • 34
13
public class MainClass {
   public static void main(String args[]) {
    System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);

    System.out.printf("Default floating-point format: %f\n", 1234567.123);
    System.out.printf("Floating-point with commas: %,f\n", 1234567.123);
    System.out.printf("Negative floating-point default: %,f\n", -1234567.123);
    System.out.printf("Negative floating-point option: %,(f\n", -1234567.123);

    System.out.printf("Line-up positive and negative values:\n");
    System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123);
  }
}

And print out:

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

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73
Torres
  • 5,330
  • 4
  • 26
  • 26
2

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

Note:

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;
Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87
1

Use DecimalFormat

 NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
 DecimalFormat decimalFormatter = (DecimalFormat) nf;
 decimalFormatter.applyPattern("#,###,###.##");
 String fString = decimalFormatter.format(myDouble);
 System.out.println(fString);
Anisuzzaman Babla
  • 6,510
  • 7
  • 36
  • 53