Java string format comma

Format Number with Commas in Java

Format number with Commas in Java

In this post, we will see how to format number with commas in java.

How To Add Commas to Number in Java

There are multiple ways to format number with commas in java. Let’s go through them.

1. Using DecimalFormat

DecimalFormat can be used by providing formatting Pattern to format number with commas in java.
Here is an example:

2. Using String’s format() method

You can also use String’s static method format() to format number with commas in java. This method is similar to System.out.printf .
Here is an example:

Читайте также:  Python переменные окружения посмотреть

For format String «%,.2f» means separate digit groups with commas and «.2» means round number to 2 decimal places in java.

Further reading:

Format double to 2 decimal places in Java
Format number with Currency in Java

3. Using System.out.printf

If you want to print number with commas, this is best way to print number with commas on console.
Here is an example:

4. Using Formatter

You can use java.util.Formatter ‘s format() method to format number with commas in java. This is similar to System.out.printf method.
Here is an example:

5. Using NumberFormat

You can also use NumberFormat ‘s setMaximumFractionDigits() to put constraint on number by decimal places and use its format() method to format number with commas in java.
Here is an example:

That’s all about How to format number with commas in java

Was this post helpful?

Share this

Author

Convert 0 to 1 and 1 to 0 in Java

Table of ContentsUsing SubtractionUsing XORUsing ternary operatorUsing addition and remainder operatorUsing array In this post, we wil see how to convert 0 to 1 and 1 to 0 in java. There are lots of ways to convert 0 to 1 and 1 to 0 in Java. Let’s go through them. Using Subtraction This is one […]

Count Number of Decimal Places in Java

Table of ContentsUsing String’s split() methodUsing String’s indexof() method In this post, we will see how to count number of decimal places in java. A Double can not have exact representation, you need to convert it to String to count number of decimal places in Java. There are multiple ways to count number of decimal […]

How to Take Integer Input in Java

Table of ContentsVariablesWhat is Integer?How to take integer input?Java Scanner classJava Program to to take Integer input in JavaConclusion This article discusses the methods to take the integer input in Java. Variables In programs, data values are reserved in memory locations that can be identified by names (identifiers). Such named memory location which temporarily reserves […]

Источник

Java String Formatting

java.util.Formatter is an interpreter for getting C language printf-style formatted strings. In Java, we usually use following methods to format console output which internally use Formatter class:

System.out.printf(String format, Object. args)
System.out.printf(Locale l, String format, Object. args)

We can also use following methods of java.lang.String to get formatted strings:

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

The ‘format’ parameter in above methods, usually consists of one or multiple formatting specifier. A formatting specifier starts with %, which is a way to specify various formatting attributes to get the desired results.

In following examples we will quickly go through different formatting options available.

n — line terminator

s or S — a String

System.out.printf("%s%n", "this is my string"); 
System.out.printf("%S%n", "this is my string");
System.out.printf("%s%n", null);
System.out.printf("%s%n", 100);
System.out.printf("%s%n", new Object());
System.out.printf("'This is the example of %s. '%n", "string");
this is my string THIS IS MY STRING null 100 java.lang.Object@247507be 'This is the example of string. '

b or B — true/false

It will convert null/false to false , everything else to true

System.out.printf("%b%n", null); 
System.out.printf("%b%n", false);
System.out.printf("%B%n", false);
System.out.printf("%b%n", true); 
System.out.printf("%b%n", "true");
System.out.printf("%b%n", "false");
System.out.printf("%b%n", "test");
System.out.printf("%b%n", 1);
System.out.printf("%b%n", 'c');
System.out.printf("%b%n", new Object());
true true true true true true true

c or C — a char

System.out.printf("%c%n", 'a'); 
System.out.printf("%C%n", 'a');
System.out.printf("%c%n", 100);
System.out.printf("%c%n", null);
System.out.printf("%c%n", "aString");
java.util.IllegalFormatConversionException: c != java.lang.String at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4331) at java.base/java.util.Formatter$FormatSpecifier.printCharacter(Formatter.java:2922) at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2810) .

Formatting with padding

For left padding, an integer is used between % and the conversion specifier:

System.out.printf("Result: %20s%n", "example");
System.out.printf("Result: %-20s%n", "example"); 
System.out.printf("%-20s result%n", "example");
Result: example example result
for (int i = 7; i < 300; i += 50) System.out.printf("[Item:%4s %-4s]%n", i, i * 10); 
>
[Item: 7 70 ] [Item: 57 570 ] [Item: 107 1070] [Item: 157 1570] [Item: 207 2070] [Item: 257 2570]

Precision

This is used to limit chars.
Syntax: x.y where x= padding (width) and y= number of chars.
(For floating numbers y is used for decimal places — next sections.)

System.out.printf("%2.2s%n", "Hi there!"); 
System.out.printf("[%6.4s]%n", "What's up?");
System.out.printf("[%-6.4s]%n", "What's up?");

d — byte/short/int/long/BigInteger formatting

System.out.printf("%d%n", 2); 
System.out.printf("%d%n", (byte) 2);
System.out.printf("%d%n", 2L);
System.out.printf("%d%n", BigInteger.valueOf(2L));
java.util.IllegalFormatConversionException: d != java.lang.Character at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4331) at java.base/java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2846) at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2800) .

Padding with zeros

0 is used just after % and then an int for padding (as we saw in ‘Formatting with padding’ above).

java.util.IllegalFormatFlagsException: Flags = '-0' at java.base/java.util.Formatter$FormatSpecifier.checkNumeric(Formatter.java:3084) at java.base/java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:3039) at java.base/java.util.Formatter$FormatSpecifier.(Formatter.java:2782) .

Comma formatted numbers

A comma is used between % and d

System.out.printf(Locale.GERMAN, "%,d", 1000000);

Always include + sign

for (int i = 1; i < 4; i++) System.out.printf("%+d%n", i); 
>

Always include parentheses for negative numbers

for (int i = 1; i < 4; i++) System.out.printf("%(d%n", -i); 
>

Always include leading space for positive numbers

Only one space is allowed:

for (int i = 1; i < 4; i++) System.out.printf("[% d]%n", i); 
>

Precision cannot be applied to integers

System.out.printf("%6.4d", 123456);
java.util.IllegalFormatPrecisionException: 4 at java.base/java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:3041) at java.base/java.util.Formatter$FormatSpecifier.(Formatter.java:2782) at java.base/java.util.Formatter.parse(Formatter.java:2621) .

f — float/double formatting

System.out.printf("%f%n", 1.33f); 
System.out.printf("%f%n", 1.33d);
System.out.printf("%f%n", Double.valueOf(1.33d));
System.out.printf("%f%n", BigDecimal.valueOf(1.33d));
1.330000 1.330000 1.330000 1.330000

Applying precisions:

Syntax: x.y, where x is width (padding) and y is decimal places. Sometimes value of x is ignored, if it’s smaller than the necessary chars (including the decimal) to display. Remember x is not to limit width but to add padding (spaces); y is to decrease/increase decimal places.

System.out.printf("[%4.2f]%n", 12.34567); 
System.out.printf("[%5.2f]%n", 12.34567);
System.out.printf("[%6.2f]%n", 12.34567);
System.out.printf("[%7.2f]%n", 12.34567);
System.out.printf("[%-7.2f]%n", 12.34567);
System.out.printf("[%7.4f]%n", 12.3);
System.out.printf("[%8.4f]%n", 12.3);
[12.35] [12.35] [ 12.35] [ 12.35] [12.35 ] [12.3000] [ 12.3000]

Always display decimal with # flag

The integer portion of the result always ends with a
decimal point (‘.’), even if the fractional portion is zero.

System.out.printf("[%#1.0f]%n", 1234d); 
System.out.printf("[%1.0f]%n", 1234d);

e or E — Scientific notation

Syntax: x.ye => y=precision and x=total width (padding)

System.out.printf("%1.2e%n", 123.45); 
System.out.printf("[%10.2e]%n", 123.45);
System.out.printf("[%-10.1e]%n", 123.45);
System.out.printf("%5.2E%n", 123.45);
1.23e+02 [ 1.23e+02] [1.2e+02 ] 1.23E+02

g or G — Scientific notation

It depends on precision and rounding.

System.out.printf("%1.2g%n", 123.45); 
System.out.printf("[%10.2g]%n", 123.45);
System.out.printf("[%-10.1g]%n", 123.45);
System.out.printf("[%-10.1G]%n", 123.45);

Index based references

A variable reference can be used as X$ just after %, where X is the index.

Following example is without referencing an index:

String test = "myString"; 
System.out.printf("%1.2s - %1.4s", test, test);
String test2 = "myString"; 
System.out.printf("%1$1.2s - %1$1.4s", test2);

Using multiple references:

System.out.printf("%2$s | %3$1.4f | %1$,d", 1333, "hello", 5.4444);

t or T — Date time formatting

System.out.printf("Hours: %tH%n", new Date()); 
System.out.printf("Mins: %tM%n", new Date());
System.out.printf("Secs: %tS%n", new Date());
Date date = new Date(); 
System.out.printf("%tH:%tM:%tS%n", date, date, date);
//using index references
System.out.printf("%1$tH:%1$tM:%1$tS%n", date);
System.out.printf("%tT", new Date());

Time in am/pm format

I — for 12 hr clock
p — for am or pm

System.out.printf("%1$tI:%1$tM %1$tp", new Date());

Time in milli/nanoseconds

L — milliseconds
N — nanoseconds

System.out.printf("%1$tT %1$tL %1$tN", new Date());

TimeZone info

z — timezone offset
Z — timezone id

System.out.printf("%1$tT %1$tz%n", new Date()); 
System.out.printf("%1$tT %1$tZ%n", new Date());

Time since epoch

s — epoch seconds
Q — epoch millis

System.out.printf("epoch sec: %1$ts%n", new Date()); 
System.out.printf("epoch millis: %1$tQ%n", new Date());
epoch sec: 1512014948 epoch millis: 1512014948440

Month

B — full month name
b — abbreviated month name
m — year of month number 01 — 12

Date dt = Date.from(ZonedDateTime.of(LocalDate.of(2017, 2, 1).atStartOfDay(), 
ZoneId.systemDefault()).toInstant());
System.out.printf("%tB%n", dt);
System.out.printf("%tb%n", dt);
System.out.printf("%tm%n", dt);

Day

A — full name
a — abbreviated
d — day of month, 01 — 31

System.out.printf("%tA%n", new Date()); 
System.out.printf("%ta%n", new Date());
System.out.printf("%td%n", new Date());

Year

Y — four digit year
y — two digit year

System.out.printf("%tY%n", new Date()); 
System.out.printf("%ty%n", new Date());

Common formats shortcuts

R — %tH:%tM
T — %tH:%tM:%tS
r — %tI:%tM:%tS %Tp
D — %tm/%td/%ty
F — %tY-%tm-%td
c — %ta %tb %td %tT %tZ %tY, e.g. Sun Jul 20 16:17:00 EDT 1969.

System.out.printf("%tR%n", new Date()); 
System.out.printf("%tT%n", new Date());
System.out.printf("%tr%n", new Date());
System.out.printf("%tD%n", new Date());
System.out.printf("%tF%n", new Date());
System.out.printf("%tc%n", new Date());
22:09 22:09:08 10:09:08 PM 11/29/17 2017-11-29 Wed Nov 29 22:09:08 CST 2017

Источник

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