删除java中的小数点

时间:2013-12-10 20:27:17

标签: java

我想存储一个名为Amount的整数,我希望它存储在便士中,所以如果用户输入11.45,它将被存储为1145.删除小数点的最佳方法是什么?我应该在Java中使用decimalFormatting吗?

修改

以字符串格式输入,将其转换为int。我会先给你一个解决方案,让你知道它是否有效,但不确定哪一个是最好的..谢谢大家。

4 个答案:

答案 0 :(得分:0)

将它乘以100并转换为int。使用十进制格式是double / float太不准确,可能是为了赚钱

答案 1 :(得分:0)

如果用户输入是字符串形式(并且格式已经过验证),那么您可以去掉小数点并将结果解释为整数(或将其保留为不带小数点的字符串)

String input = "11.45";
String stripped = input.replace(".", ""); // becomes "1145"
int value = Integer.parseInt(stripped);

如果它已经是float,那么只需乘以100并进行投射,如@ user1281385所示。

答案 2 :(得分:-1)

经过测试并正常工作。即使用户输入的数字没有小数,它也会保持不变。

double x = 11.45; // number inputted

String s = String.valueOf(x); // String value of the number inputted
int index = s.indexOf("."); // find where the decimal is located

int amount = (int)x; // intialize it to be the number inputted, in case its an int

if (amount != x) // if the number inputted isn't an int (contains decimal)
    // multiply it by 10 ^ (the number of digits after the decimal place)
    amount = (int)(x * Math.pow(10,(s.length() - 1 - index)));

System.out.print(amount); // output is 1145

// if x was 11.4500, the output is 1145 as well
// if x was 114500, the output is 114500

答案 3 :(得分:-1)

如何转换为float,乘以100,然后转换为int?

String pound = "10.45"; // user-entered string
int pence = (int)Math.round(Float.parseFloat(pound) * 100);

这可能也很有用:Best way to parseDouble with comma as decimal separator?