【问题标题】:How can I convert an implied decimal point to a real decimal point in java?如何在java中将隐含的小数点转换为真正的小数点?
【发布时间】:2018-09-07 02:56:02
【问题描述】:

我正在尝试将字符串转换为货币。例如,我想将字符串 12579500 转换为 $125,795.00。我正在尝试使用 DecimalFormat("$#,###.00) 将字符串转换为双精度字符串,但最终得到的是 $12,579,500.00。

如何将字符串末尾的最后 2 个数字设置为小数点?

这是我目前的代码。

DecimalFormat df = new DecimalFormat("$#,###.00");
double ticketPriceNum = Double.parseDouble(ticketPrice);
System.out.print(df.format(ticketPriceNum));

【问题讨论】:

  • 格式化前将double的值除以100。
  • 你试过把ticketPriceNum除以100吗?
  • 行得通。谢谢!

标签: java decimal decimalformat


【解决方案1】:

这将确保您的字符串减少 2 个字符

    DecimalFormat df = new DecimalFormat("$#,###.00");
    double ticketPriceNum = Double.parseDouble(ticketPrice.substring(0, ticketPrice.length()- 2));
    System.out.print(df.format(ticketPriceNum));

【讨论】:

    【解决方案2】:

    请试试这个

    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("$#,###,##.00");
        //if last two digits of ticketprice should be decimal points
        double ticketPriceNum = Double.parseDouble(ticketPrice/100);
    
        System.out.println(df.format(ticketPriceNum  ));
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 2011-11-25
      • 2012-02-05
      • 1970-01-01
      • 2015-08-25
      • 2022-11-17
      • 1970-01-01
      相关资源
      最近更新 更多