解析双精度值 - 字符串时遇到困难



感谢您抽出宝贵时间回答我的问题。

我有一个double值(假设 22.35(。我需要将其解析为String并得到 2235。以下代码无法正常工作。

double totalPrice = 22.35;
DecimalFormat df = new DecimalFormat("#.##");
String[] temp = df.format(totalPrice).split(".");
String amount = temp[0] + temp[1];

我不断收到异常ArrayIndexOutOfBounds.还有什么方法可以做到这一点?提前感谢!

如果您的值在乘以 100 后没有超过 100,MAX_INT,将它们相乘:

double totalPrice = 22.35;
int iPrice = (int) (totalPrice * 100);
String sPrice = "" + iPrice;

怎么样:

double totalPrice = 22.35;
DecimalFormat df = new DecimalFormat("#.##");
String price = df.format(totalPrice).replace(".", "");

也许你可以这样做:只需将正则表达式 "." 更改为 " \."!

String[] temp = df.format(totalPrice).split("\.");

无论您尝试将其应用于多高的数字,这都将起作用:

double num = 22.35;
String concatenate = "" + num;
String parsedNum = concatenate.replace(".", "");

希望这对你有帮助。

最新更新