在没有正则表达式的情况下将双精度表示为整数

Represent double as integer without regex

我正在为 android 开发一个计算器。 有一个名为 resultdouble 字段,然后我将其放入 TextView

如果说 result = 20.0 那么我必须将其表示为 20(没有点和零)。如果 result = 20.0001 则应保持不变。

现在我用正则表达式来做,但我想这不是个好主意。 如果 double 实际上是一个整数(点后没有数字),是否有另一种表示没有点和零的 double 的方法?

希望我能理解你的问题。也许这会帮助您解决问题。

    double d = 20.0001;
    if ((int) d == d)
        System.out.println((int) d);
    else
        System.out.println(d);

您可以像这样使用模数除法:

if((**doublevariablehere** % 1) == 0)
{
}

代码取自here

显式类型转换如何

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

使用(d % 1 == 0) { 检查你的double是否没有小数部分,然后使用intValue()方法得到integer来自 Double!

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

您可以将结果输出为格式化字符串:

public static String fmt(double d)
{
    if(d == (long) d)
        return String.format("%d",(long)d);
    else
        return String.format("%s",d);
}

使用模数 % 运算符。 假设您的计算值为:

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

检查你的 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