我正在为android
开发一个计算器。
拥有一个名为double
的{{1}}字段,然后我将其放入result
。
如果说TextView
,那么我必须将其表示为result = 20.0
(没有点和零)。如果20
应该显示不变。
现在我用正则表达式做,但我想这不是一个好主意。 如果double实际上是一个整数(在点之后没有数字),还有另一种方法来表示没有点的双精度和零吗?
答案 0 :(得分:1)
我希望我能理解你的问题。也许这可以帮助您解决问题。
double d = 20.0001;
if ((int) d == d)
System.out.println((int) d);
else
System.out.println(d);
答案 1 :(得分:1)
显式类型转换
double y=anyValue;
int x = (int) y;
if(x==y)
log.debug(x);
else
log.debug(y);
对于输入y=3.00
,输出将为3
对于输入y=3.0001
,输出将为3.0001
答案 2 :(得分:0)
使用(d % 1 == 0) {
检查您的double是否没有小数部分,然后使用intValue()
方法从{{integer
中取出Double
1}}!
class testDouble {
public static void main(String[] args) {
Double result = 20.001;
if (result % 1 == 0) {
System.out.println(result + " Can be turned into integer, has no decimal part");
}
else {
System.out.println(result + " Can not be turned into integer, has decimal part");
}
result = 20.000;
if (result % 1 == 0) {
System.out.println(result + " Can be turned into integer, has no decimal part");
int intOfDouble = result.intValue();
System.out.println(result + " Can be turned into integer " + intOfDouble);
}
}
}
输出:
20.001 Can not be turned into integer, has decimal part
20.0 Can be turned into integer, has no decimal part
20.0 Can be turned into integer 20
答案 3 :(得分:0)
您可以将结果输出为格式化字符串:
public static String fmt(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
答案 4 :(得分:0)
使用模数%
运算符。
我们说你的计算值是:
double result;
if (x % 1) == 0
then you must have a whole number
and you can use (int) result to cast it and int value
else //your number is not a whole number
you will just use the result as is
答案 5 :(得分:0)
针对广告double
检查您的result
(long) result
并创建一个字符串,以便通过单行显示:
double r;
String s;
for (int i = 2; i <= 3; i++) {
r = 100d / i;
// this is the essential line, all others are just testing noise
s = r > (long) r ? String.valueOf(r) : String.valueOf((long) r);
// -------------------------------------------------------------
System.out.println(s);
}
打印:
50
33.333333333333336
答案 6 :(得分:-1)