java 将字符串小数 (2.9) 更改为 Int 或 Long 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14347642/
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
Changing a String decimal (2.9) to Int or Long issues
提问by Tazmanian Tad
Okay, I'm fairly new to java but I'm learning quickly(hopefully). So anyway here is my problem:
好的,我对 Java 还很陌生,但我学得很快(希望如此)。所以无论如何这是我的问题:
I have a string(For example we will use 2.9), I need to change this to either int or long or something similar that I can use to compare to another number.
我有一个字符串(例如我们将使用 2.9),我需要将其更改为 int 或 long 或类似的东西,以便我可以用来与另一个数字进行比较。
As far as I know int doesn't support decimals, I'm not sure if long does either? If not I need to know what does support decimals.
据我所知 int 不支持小数,我不确定 long 是否也支持?如果不是,我需要知道什么支持小数。
This is the error: java.lang.NumberFormatException: For input string: "2.9"
with both Interger.parseInt and Long.parseLong
这是错误:java.lang.NumberFormatException: For input string: "2.9"
同时使用 Interger.parseInt 和 Long.parseLong
So any help would be appreciated!
所以任何帮助将不胜感激!
采纳答案by Fritz
Both int
and long
are integer values (being long
the representation of a long integerthat is an integer with a higher capacity). The parsing fails because those types do not support a decimal part.
两个int
和long
是整数值(即long
一个的表示长整型是具有更高容量的整数)。解析失败,因为这些类型不支持小数部分。
If you were to use them and enforce a casting you're relinquishing the decimal part of the number.
如果您要使用它们并强制执行强制转换,那么您将放弃数字的小数部分。
double iAmADouble = 100 / 3;
int iWasADouble = (int)iAmADouble; //This number turns out to be 33
Use double
or float
instead.
使用double
或float
代替。
回答by kosa
You can't directly get int
(or) long
from decimal point value.
您不能直接从小数点值获取int
(或)long
。
One approach is:
一种方法是:
First get a double value and then get int (or) long.
首先得到一个double值,然后得到int(或)long。
Example:
例子:
int temp = Double.valueOf("20.2").intValue();
System.out.println(temp);
output:
输出:
20
回答by GriffeyDog
int
and long
are both integer datatypes, 32-bit and 64-bit respectively. You can use float
or double
to represent floating point numbers.
int
和long
都是整数数据类型,分别是 32 位和 64 位。您可以使用float
或double
来表示浮点数。
回答by partlov
That string (2.9) is neither integer
nor long
. You should use some decimal point types, for example float
or double
.
该字符串 (2.9) 既不是 也不integer
是long
。您应该使用一些小数点类型,例如float
或double
。