【问题标题】:Format Bigdecimal in Java [duplicate]在Java中格式化Bigdecimal [重复]
【发布时间】:2017-06-25 21:20:42
【问题描述】:

我想根据以下规则格式化 BigDecimal 值:

25 => 25
25,1 => 25,10
25,10 => 25,10
25,12 = > 25,12

我搜索了论坛,但没有找到匹配的问题(hereherehere),我查看了 BigDecimalNumberFormat 的 javadoc,但不知道如何执行此操作。

编辑: 今天我这样做:

NumberFormat currencyFormat02 = NumberFormat.getCurrencyInstance(locale);
currencyFormat02.setMinimumFractionDigits(0);
currencyFormat02.setMaximumFractionDigits(2);
currencyFormat02.setGroupingUsed(false);
BigDecimal bd = new BigDecimal("25 or 25,1 or 25,10 or 25,12");
String x =currencyFormat02.format(bd);

x 应该像上面那样打印,但不是。

【问题讨论】:

  • 示例很棒,但您还需要指定您要执行的操作。
  • 我已经更新了问题
  • 你还没有描述你的目标。
  • @OleV.V.是的,这是一个解决方案!感谢您提供。

标签: java format bigdecimal


【解决方案1】:

可能不是最有效的,但您可以尝试以下方法:

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

class Main {
  public static void main(String[] args) {
    BigDecimal ex1 = new BigDecimal("25");
    BigDecimal ex2 = new BigDecimal("25.1");
    BigDecimal ex3 = new BigDecimal("25.10");
    BigDecimal ex4 = new BigDecimal("25.12");
    printCustomBigDecimalFormat(ex1);
    printCustomBigDecimalFormat(ex2);
    printCustomBigDecimalFormat(ex3);
    printCustomBigDecimalFormat(ex4);
  }

  public static void printCustomBigDecimalFormat(BigDecimal bd) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
    symbols.setDecimalSeparator(',');
    DecimalFormat df = new DecimalFormat("##.00", symbols);
    if(containsDecimalPoint(bd)) {
      System.out.println(df.format(bd));
    } else {
      System.out.println(bd);
    }
  }

  private static boolean containsDecimalPoint(BigDecimal bd) {
    return bd.toString().contains(".");
  }
}

输出:

25
25,10
25,10
25,12

试试here!

【讨论】:

【解决方案2】:

然后您需要区分表示“整数”的 BigDecimal 值;和那些没有的。

类似:

BigDecimal someNumber = ...
if (someNumber.toBigIntegerExact()) {
 // go for the 25 kind of formatting
} else {
 // go for the 25.xx kind of formatting

“25.xx”格式很好地描述了here(或在莱昂纳多的另一个答案中)

【讨论】:

    【解决方案3】:

    要用 NumberFormat 格式化 BigDecimal,你需要先设置 Locale,试试这样:

    String strToFormat = "25.10";
    Locale loc = new Locale("en","US");
    
    DecimalFormat numFormat = (DecimalFormat)NumberFormat.getInstance(loc);
    numFormat.setParseBigDecimal(true);
    BigDecimal yourValue = (BigDecimal)numFormat.parse(strToFormat, new ParsePosition(0));
    
    System.out.println("Value : " + yourValue);
    

    结果:

    Value : 25.10
    

    【讨论】:

    • 这会将 25 格式化为“25,00”
    • 是的,这不正确。
    • 运行代码后编辑测试并添加结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 2019-04-01
    • 2012-10-02
    • 2017-10-27
    • 1970-01-01
    相关资源
    最近更新 更多