【问题标题】:Number/Currency Formatting数字/货币格式
【发布时间】:2013-01-15 08:25:33
【问题描述】:

我确实有像+000000027511,00 这样格式的保加利亚货币。我想将此格式转换为27511.00,我已经尝试过并使用子字符串组合和正则表达式,是否有任何模式或正则表达式可以做更多简化方式?

我尝试过的实现,

String currency= "+000000027511"; // "[1234]" String
String currencyFormatted=currency.substring(1);
System.out.println(currencyFormatted.replaceFirst("^0+(?!$)", ""));

【问题讨论】:

  • 取一个大数并使用setScale和2,或将其解析为浮点数并使用NumberFormat

标签: java regex currency


【解决方案1】:

使用Double.valueOf + DecimalFormat.format,或DecimalFormat.parse + format,或BigDecimal,您可以这样做。

  // method 1 (parsing to Float)
  String s = "+000000027511,00".replace(",", ".");
  Double f = Double.valueOf(s);
  DecimalFormat df = new DecimalFormat("#########0.00");
  String formatted = df.format(f);
  System.out.println(formatted);

  // method 2 (parsing using Decimal Format)
  s = "+000000027511,00";
  DecimalFormat df2 = new DecimalFormat("+#########0.00;-#########0.00");
  Number n = df2.parse(s);
  df = new DecimalFormat("#########0.00");
  formatted = df.format(n);
  System.out.println(formatted);

  // method 3 (using BigDecimal)
  BigDecimal b = new BigDecimal(s.replace(",", "."));
  b.setScale(2, RoundingMode.HALF_UP);
  System.out.println(b.toPlainString());

将打印

27511.00
27511.00
27511.00

【讨论】:

  • 在 99% 的情况下,我会使用 double 而不是 float
【解决方案2】:

类似这样的:

String s = "+000000027511,00";
String r = s.replaceFirst("^\\+?0*", "");
r = r.replace(',', '.');

【讨论】:

    【解决方案3】:

    试试

        String s = "+000000027511,00";
        s = s.replace("+", "").replaceAll("^0+", "").replace(',', '.');
        System.out.println(s);
    

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 2011-01-23
      • 1970-01-01
      • 2020-09-16
      • 2022-11-14
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多