Java 如何格式化字符串数字以包含逗号和四舍五入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3672731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:21:45  来源:igfitidea点击:

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

javastringnumbersdecimalnumber-formatting

提问by Sheehan Alam

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?

我该如何格式化?

采纳答案by NullUserException

You might want to look at the DecimalFormatclass; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57instead).

你可能想看看这个DecimalFormat类;它支持不同的语言环境(例如:在某些国家/地区会被格式化为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));

回答by Aaron Novstrup

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)

回答by Jeremy Trifilo

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

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. 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.

我还应该指出这不处理十进制支持,但对整数值非常有用。上面的示例将显示“1.23M”作为输出。我可能可以添加十进制支持,但从那时起我就没有看到它有太多用处,我不妨将它合并到一个 BigInteger 类型的类中,该类处理用于数学计算的压缩 char[] 数组。

回答by Venod Raveendran

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. Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.

因此,#,##0.00 格式对我来说效果很好。在部署到生产系统之前,始终测试不同的数字,例如 0 / 100 / 2334.30 和负数。

回答by Jitendra Nath

you can also use below solution -

您还可以使用以下解决方案 -

public static String getRoundOffValue(double value){

        DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
        return df.format(value);
}

回答by user3314142

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

回答by Peter Griffin

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. Either way works.

DecimalFormat 构造函数中的最后两个 # 符号也可以是 0。无论哪种方式都有效。

回答by Greg H

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

回答by John Paker

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

回答by Ben Watson

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.

鉴于这是 Google 对 的排名第一的结果format number commas java,这里有一个适用于使用整数而不关心小数的人的答案。

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

outputs:

输出:

2,000,000