开发者

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 ano开发者_StackOverflow中文版ther number is :

long number = 139454

then output should be

1.394,54


try Formatter

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

output

21.474.836,47


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.


    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.


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜