Java:将科学记数法转换为常规 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2546147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Convert scientific notation to regular int
提问by user305210
How do I convert scientific notation to regular int For example: 1.23E2 I would like to convert it to 123
如何将科学记数法转换为常规 int 例如:1.23E2 我想将其转换为 123
Thanks.
谢谢。
采纳答案by Péter T?r?k
If you have your value as a String, you could use
如果您的值是字符串,则可以使用
int val = new BigDecimal(stringValue).intValue();
回答by codaddict
You can just cast it to int
as:
您可以将其转换int
为:
double d = 1.23E2; // or float d = 1.23E2f;
int i = (int)d; // i is now 123
回答by Uri
I am assuming you have it as a string.
我假设你把它作为一个字符串。
Take a look at the DecimalFormatclass. Most people use it for formatting numbers as strings, but it actually has a parse method to go the other way around! You initialize it with your pattern (see the tutorial), and then invoke parse() on the input string.
看看DecimalFormat类。大多数人使用它来将数字格式化为字符串,但它实际上有一个 parse 方法可以反过来!你用你的模式初始化它(参见教程),然后对输入字符串调用 parse() 。
回答by Pops
Check out DecimalFormat.parse().
Sample code:
示例代码:
DecimalFormat df = new DecimalFormat();
Number num = df.parse("1.23E2", new ParsePosition(0));
int ans = num.intValue();
System.out.println(ans); // This prints 123
回答by divinedragon
You can also use something like this.
你也可以使用这样的东西。
(int) Double.parseDouble("1.23E2")