Beginner
Beginner

Reputation: 875

How to get this number format in java?

Lets say I am having a number as follows :

long number = 32301672060;

I want the following the format for the number :

323.016.720,60

i.e the last two digits should be separated by comma and then dot between every three digits.

Suppose the another number is :

long number = 139454

then output should be

1.394,54

Upvotes: 0

Views: 1469

Answers (4)

Hans Olsson
Hans Olsson

Reputation: 54999

Cast the value to a double, divide it by 100 (to get the 2 decimal points) and then set the current locale to something like de_DE and use NumberFormat to format it for you.

Edit: As noted by Behrang in the comments, after converting the long to a double, it should only be used for display purposes as further calculations using this might result in loss of precision.

Upvotes: 2

kan
kan

Reputation: 28951

Use decimals.

final BigDecimal dec = new BigDecimal(BigInteger.valueOf(32301672060L), 2);
System.out.println(new DecimalFormat("###,##0.00").format(dec));

or instead of the pattern, better to use locale's formats, e.g.

System.out.println(NumberFormat.getCurrencyInstance(Locale.US).format(dec));

or

System.out.println(NumberFormat.getNumberInstance(Locale.US).format(dec));

Upvotes: 0

Dragon8
Dragon8

Reputation: 1805

    long number = 32301672060L;

    NumberFormat nb = NumberFormat.getNumberInstance(Locale.GERMAN);
    nb.setMinimumFractionDigits(2);

    System.out.println(nb.format((double)number/100));

This should work for you. The German Local is important to have the point as decimal point and the comma at the last 2 digits.

Upvotes: 0

oliholz
oliholz

Reputation: 7507

try Formatter

long number = Integer.MAX_VALUE;
System.out.printf(Locale.GERMAN, "%,.2f", new Double(number/100d) );

output

21.474.836,47

Upvotes: 2

Related Questions