如何在Java中将隐含的小数点转换为实际的小数点?

时间:2018-09-07 02:56:03

标签: java decimal decimalformat

我正在尝试将字符串转换为货币。例如,我想将字符串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));

2 个答案:

答案 0 :(得分:0)

请尝试

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

}

答案 1 :(得分:0)

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

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