如何格式化字符串编号以使用逗号和圆形?

时间:2022-02-05 18:17:54

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?

我该如何格式化呢?

10 个解决方案

#1


210  

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

您可能想要查看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));

#2


30  

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)

#3


25  

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

#4


10  

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.
  • 逗号格式化例如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. 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 []数组。

#5


6  

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

#6


5  

you can also use below solution -

你也可以使用以下解决方案 -

public static String getRoundOffValue(double value){

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

#7


3  

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。无论哪种方式都有效。

#8


3  

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

#9


2  

The first answer works very well, but for ZERO / 0 it will format as .00

第一个答案非常有效,但对于ZERO / 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和负数。

#10


-2  

This class is for simple Indian price formatter

本课程适用于简单的印度价格格式器

public class Test {

public static void main (String a[]){
    System.out.println(priceFormatter("10023"));    
}
/**
 * This method is to convert the price into Indian price
 * separator format
 * @param inputPrice
 * @return
 */
public static String priceFormatter(String inputPrice){
    try {
        if(!isNumeric(inputPrice)){
            return inputPrice;
        }
        // to check if the number is a decimal number
        String newPrice = "",afterDecimal = "";
        if(inputPrice.indexOf('.') != -1){
            newPrice = inputPrice.substring(0,inputPrice.lastIndexOf('.'));
            afterDecimal = inputPrice.substring(inputPrice.lastIndexOf('.'));
        }else{
            newPrice = inputPrice;
        }
        int length = newPrice.length();
        if (length < 4) {
            return inputPrice;
        }
        // to check whether the length of the number is even or odd
        boolean isEven = false;
        if (length % 2 == 0) {
            isEven = true;
        }
        // to calculate the comma index
        char ch[] = new char[length + (length / 2 - 1)];
        if (isEven) {
            for (int i = 0, j = 0; i < length; i++) {
                ch[j++] = inputPrice.charAt(i);
                if (i % 2 == 0 && i < (length - 3)) {
                    ch[j++] = ',';
                }
            }
        } else {
            for (int i = 0, j = 0; i < length; i++) {
                ch[j++] = inputPrice.charAt(i);
                if (i % 2 == 1 && i < (length - 3)) {
                    ch[j++] = ',';
                }
            }
        }
        // conditional return based on decimal number check
        return afterDecimal.length() > 0 ? String.valueOf(ch) + afterDecimal : String.valueOf(ch);

    } catch(NumberFormatException ex){
        ex.printStackTrace();
        return inputPrice;
    }
      catch (Exception e) {
        e.printStackTrace();
        return inputPrice;
    }
}

}

#1


210  

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

您可能想要查看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));

#2


30  

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)

#3


25  

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

#4


10  

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.
  • 逗号格式化例如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. 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 []数组。

#5


6  

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

#6


5  

you can also use below solution -

你也可以使用以下解决方案 -

public static String getRoundOffValue(double value){

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

#7


3  

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。无论哪种方式都有效。

#8


3  

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

#9


2  

The first answer works very well, but for ZERO / 0 it will format as .00

第一个答案非常有效,但对于ZERO / 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和负数。

#10


-2  

This class is for simple Indian price formatter

本课程适用于简单的印度价格格式器

public class Test {

public static void main (String a[]){
    System.out.println(priceFormatter("10023"));    
}
/**
 * This method is to convert the price into Indian price
 * separator format
 * @param inputPrice
 * @return
 */
public static String priceFormatter(String inputPrice){
    try {
        if(!isNumeric(inputPrice)){
            return inputPrice;
        }
        // to check if the number is a decimal number
        String newPrice = "",afterDecimal = "";
        if(inputPrice.indexOf('.') != -1){
            newPrice = inputPrice.substring(0,inputPrice.lastIndexOf('.'));
            afterDecimal = inputPrice.substring(inputPrice.lastIndexOf('.'));
        }else{
            newPrice = inputPrice;
        }
        int length = newPrice.length();
        if (length < 4) {
            return inputPrice;
        }
        // to check whether the length of the number is even or odd
        boolean isEven = false;
        if (length % 2 == 0) {
            isEven = true;
        }
        // to calculate the comma index
        char ch[] = new char[length + (length / 2 - 1)];
        if (isEven) {
            for (int i = 0, j = 0; i < length; i++) {
                ch[j++] = inputPrice.charAt(i);
                if (i % 2 == 0 && i < (length - 3)) {
                    ch[j++] = ',';
                }
            }
        } else {
            for (int i = 0, j = 0; i < length; i++) {
                ch[j++] = inputPrice.charAt(i);
                if (i % 2 == 1 && i < (length - 3)) {
                    ch[j++] = ',';
                }
            }
        }
        // conditional return based on decimal number check
        return afterDecimal.length() > 0 ? String.valueOf(ch) + afterDecimal : String.valueOf(ch);

    } catch(NumberFormatException ex){
        ex.printStackTrace();
        return inputPrice;
    }
      catch (Exception e) {
        e.printStackTrace();
        return inputPrice;
    }
}

}