【问题标题】:How can i format Double value comma separtely [duplicate]如何单独格式化双值逗号 [重复]
【发布时间】:2023-03-25 23:21:01
【问题描述】:

我目前正在开发 Spring MVC 中的工资支付模块,在应用程序级别,我将我的工资数据存储为 double 类型,eg double amount=32690597

我想将其格式化为 32,690,597,使其更具可读性。

建议我最好的解决方案,谢谢

【问题讨论】:

    标签: java


    【解决方案1】:

    使用DecimalFormat 解决这个问题。

    double amount = 32690597;
    //create pattern for decimal format
    String pattern = "###,###";
    DecimalFormat decimalFormat = new DecimalFormat(pattern);
    
    //change dot with comma
    String formattedNumber = decimalFormat.format(amount).replace(".",",");
    

    详细的十进制格式化键;

    0   A digit - always displayed, even if number has less digits (then 0 is displayed)
    #   A digit, leading zeroes are omitted.
    .   Marks decimal separator
    ,   Marks grouping separator (e.g. thousand separator)
    E   Marks separation of mantissa and exponent for exponential formats.
    ;   Separates formats
    -   Marks the negative number prefix
    %   Multiplies by 100 and shows number as percentage
    ?   Multiplies by 1000 and shows number as per mille
    ¤   Currency sign - replaced by the currency sign for the Locale. Also makes formatting use the monetary decimal separator instead of normal decimal separator. ¤¤ makes formatting use international monetary symbols.
    X   Marks a character to be used in number prefix or suffix
    '   Marks a quote around special characters in prefix or suffix of formatted number.
    

    一些例子

    Pattern      Number        Formatted String
    ###.###      123.456       123.456
    ###.#        123.456       123.5
    ###,###.##   123456.789    123,456.79
    000.###      9.95          009.95
    ##0.###      0.95          0.95
    

    【讨论】:

    • 哇,很好的解释,但是我的问题现在已经解决了,但我仍然支持你的解释。
    【解决方案2】:
    System.out.println(String.format("%1$,.0f", amount));
    

    String formatAmount = new DecimalFormat("#,###,###,###,###").format(amount);
    

    或 - Java 8

    NumberFormat numberFormatter = NumberFormat.getNumberInstance(Locale.ENGLISH);
    String formatAmount = numberFormatter.format(amount);
    

    【讨论】:

    • 特别感谢 java 8
    【解决方案3】:
    static String formatDouble(double input){
        String inputString = new String(Double.toString(input));
        char[] array= inputString.toCharArray();
        StringBuilder str = new StringBuilder("");
        for(int i = array.length-1; i >= 0; i--){
            str.insert(0, array[i]);
                if(i % 3 == 0 && i != 0){
                str.insert(0, ",");
                }
            }
        return str.toString();
        }
    

    希望对你有帮助

    更好地使用 String.format

    【讨论】:

    • 非常感谢亲爱的,这似乎是传统的和手动的方式来达到同样的效果,它确实提高了初学者的学习能力,是的,恭喜你成为行为准则的一部分。一切顺利
    • 谢谢,我更新了代码,因为它依赖于编译器的某些方面。上面更新的示例应该适用于任何地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2016-02-14
    • 1970-01-01
    • 2016-11-11
    • 2010-10-16
    • 2017-04-03
    相关资源
    最近更新 更多