简体   繁体   English

如何格式化字符串数字以包含逗号和圆角?

[英]How can I format a String number to have commas and round?

What is the best way to format the following number that is given to me as a String?将给我的以下数字格式化为字符串的最佳方法是什么?

String number = "1000500000.574" //assume my value will always be a String

I want this to be a String with the value: 1,000,500,000.57我希望这是一个字符串,其值为: 1,000,500,000.57

How can I format it as such?我该如何格式化它?

You might want to look at the DecimalFormat class;您可能想查看DecimalFormat类; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).它支持不同的语言环境(例如:在某些国家/地区,格式1.000.500.000,57改为1.000.500.000,57 )。

You also need to convert that string into a number, this can be done with:您还需要将该字符串转换为数字,这可以通过以下方式完成:

double amount = Double.parseDouble(number);

Code sample:代码示例:

String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");

System.out.println(formatter.format(amount));

This can also be accomplished using String.format(), which may be easier and/or more flexible if you are formatting multiple numbers in one string.这也可以使用 String.format() 来完成,如果您在一个字符串中格式化多个数字,这可能更容易和/或更灵活。

    String number = "1000500000.574";
    Double numParsed = Double.parseDouble(number);

    System.out.println(String.format("The input number is: %,.2f", numParsed));
    // Or
    String numString = String.format("%,.2f", numParsed);

For the format string "%,.2f" - "," means separate digit groups with commas, and ".2" means round to two places after the decimal.对于格式字符串"%,.2f" - "," 表示用逗号分隔数字组,".2" 表示四舍五入到小数点后两位。

For reference on other formatting options, see https://docs.oracle.com/javase/tutorial/java/data/numberformat.html有关其他格式选项的参考,请参阅https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Once you've converted your String to a number, you can use将 String 转换为数字后,您可以使用

// format the number for the default locale
NumberFormat.getInstance().format(num)

or或者

// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)

Given this is the number one Google result for format number commas java , here's an answer that works for people who are working with whole numbers and don't care about decimals.鉴于这是format number commas java的排名第一的谷歌结果,这是一个适用于使用整数而不关心小数的人的答案。

String.format("%,d", 2000000)

outputs:输出:

2,000,000

I've created my own formatting utility.我已经创建了自己的格式化实用程序。 Which is extremely fast at processing the formatting along with giving you many features :)这在处理格式方面非常快,并为您提供了许多功能:)

It supports:它支持:

  • Comma Formatting Eg 1234567 becomes 1,234,567.逗号格式 例如 1234567 变为 1,234,567。
  • Prefixing with "Thousand(K),Million(M),Billion(B),Trillion(T)".前缀为“千(K),百万(M),十亿(B),万亿(T)”。
  • Precision of 0 through 15. 0 到 15 的精度。
  • Precision re-sizing (Means if you want 6 digit precision, but only have 3 available digits it forces it to 3).精确调整大小(意味着如果您想要 6 位精度,但只有 3 个可用数字,它会将其强制为 3)。
  • Prefix lowering (Means if the prefix you choose is too large it lowers it to a more suitable prefix).前缀降低(意味着如果您选择的前缀太大,则会将其降低为更合适的前缀)。

The code can be found here .代码可以在这里找到。 You call it like this:你这样称呼它:

public static void main(String[])
{
   int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
   String formatted = ValueFormat.format(1234567, settings);
}

I should also point out this doesn't handle decimal support, but is very useful for integer values.我还应该指出这不处理十进制支持,但对整数值非常有用。 The above example would show "1.23M" as the output.上面的示例将显示“1.23M”作为输出。 I could probably add decimal support maybe, but didn't see too much use for it since then I might as well merge this into a BigInteger type of class that handles compressed char[] arrays for math computations.我可能可以添加十进制支持,但从那时起我就没有看到它有太多用处,我不妨将它合并到一个 BigInteger 类型的类中,该类处理用于数学计算的压缩 char[] 数组。

you can also use the below solution您也可以使用以下解决方案

public static String getRoundOffValue(double value){
    DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
    return df.format(value);
}
public void convert(int s)
{
    System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}

public static void main(String args[])
{
    LocalEx n=new LocalEx();
    n.convert(10000);
}

You can do the entire conversion in one line, using the following code:您可以使用以下代码在一行中完成整个转换:

String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));

The last two # signs in the DecimalFormat constructor can also be 0s. DecimalFormat 构造函数中的最后两个 # 符号也可以是 0。 Either way works.无论哪种方式都有效。

The first answer works very well, but for ZERO / 0 it will format as .00第一个答案效果很好,但对于零 / 0 它将格式化为 .00

Hence the format #,##0.00 is working well for me.因此,#,##0.00 格式对我来说效果很好。 Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.在部署到生产系统之前,始终测试不同的数字,例如 0 / 100 / 2334.30 和负数。

Here is the simplest way to get there:这是到达那里的最简单方法:

String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result)); 

output: 10,987,655.88输出:10,987,655.88

According to chartGPT根据图表GPT

Using DecimalFormat:使用十进制格式:

DecimalFormat df = new DecimalFormat("#,###.00");
String formattedNumber = df.format(yourNumber);

Using NumberFormat:使用数字格式:

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setGroupingUsed(true);
String formattedNumber = nf.format(yourNumber);

Using String.format():使用 String.format():

String formattedNumber = String.format("%,.2f", yourNumber);

Note: In all the above examples, "yourNumber" is the double value that you want to format with a comma.注意:在上述所有示例中,“yourNumber”是您要使用逗号格式化的双精度值。 The ".2f" in the format string indicates that the decimal places should be rounded to 2 decimal places.格式字符串中的“.2f”表示小数点四舍五入到小数点后两位。 You can adjust this value as needed.您可以根据需要调整此值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM