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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:57:32  来源:igfitidea点击:

Changing a String decimal (2.9) to Int or Long issues

java

提问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 intand longare integer values (being longthe representation of a long integerthat is an integer with a higher capacity). The parsing fails because those types do not support a decimal part.

两个intlong是整数值(即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 doubleor floatinstead.

使用doublefloat代替。

回答by kosa

You can't directly get int(or) longfrom 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

intand longare both integer datatypes, 32-bit and 64-bit respectively. You can use floator doubleto represent floating point numbers.

intlong都是整数数据类型,分别是 32 位和 64 位。您可以使用floatdouble来表示浮点数。

回答by partlov

That string (2.9) is neither integernor long. You should use some decimal point types, for example floator double.

该字符串 (2.9) 既不是 也不integerlong。您应该使用一些小数点类型,例如floatdouble