我如何格式化数字到固定区域设置? [英] How can I format a number to the fixed locale?

查看:134
本文介绍了我如何格式化数字到固定区域设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能每3位从去年启动后插入到一个字符串逗号(,)?

How can I insert to a string comma (,) after every 3 position starting from last?

input             desired output    

9876567846678     9,876,567,846,678  
567               567
1234              1,234

我使用了一个类似的方法首先由三个位置将整个字符串,然后同时由三个三位合并附加昏迷。

I used one method like first divide the whole string by three position and then while merging appending coma by three three position.

有没有更好的解决办法?是否有可用的功能做这一招在java中?

Is there any better solution? Is there function available to do this trick in java?

编辑:结果
LAS_VEGAS答案将格式化根据区域设置的数量。但我想它格式化为一个固定的区域......结果
我该怎么办THT?

Edit :
LAS_VEGAS answer will format the number based on the locale. But i want to format it to a fixed locale ...
how can i do tht?

推荐答案

是的,有一个绝招在Java中:

Yes, there is a "trick" in Java:

public static String addCommas(int num) {
    DecimalFormat df = new DecimalFormat();
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setGroupingSeparator(',');
    df.setDecimalFormatSymbols(dfs);
    return df.format(num);
}

System.out.println(addCommas(123456789));

编辑:
如果你希望你的输出独立于语言环境可以使用下面的方法。它从端开始,所以没有需要扭转字符串并应该是相当有效的:

In case you want your output to be independent from locale you can use the method below. It starts from the end so there is no need to reverse the string and should be quite efficient:

public static String addCommas(int num) {
    StringBuilder s = new StringBuilder(Integer.toString(num));
    for(int i = s.length() - 3; i > 0; i -= 3) {
        s.insert(i, ',');
    }
    return s.toString();
}

这篇关于我如何格式化数字到固定区域设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆