如何从Java中的'double'类型的值中删除十进制值

Sud*_*hir 40 java

我正在调用一个名为"calculateStampDuty"的方法,该方法将返回要在房产上支付的印花税金额.百分比计算工作正常,并返回正确的值"15000.0".但是,我想将前端用户的值显示为"15000",因此只想删除小数和之后的任何值.如何才能做到这一点?我的代码如下:

float HouseValue = 150000;
double percentageValue;

percentageValue = calculateStampDuty(10, HouseValue);

private double calculateStampDuty(int PercentageIn, double HouseValueIn){
    double test = PercentageIn * HouseValueIn / 100;
    return test;
}
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

  • 创建一个新的字符串,将double值转换为字符串,如下所示:

    String newValue = percentageValue.toString();

  • 我尝试在String对象上使用'valueOf'方法,如下所示:

    String total2 = String.valueOf(percentageValue);

但是,我只是无法获得没有小数位的值.在这个例子中有没有人知道如何获得"15000"而不是"15000.0"?

谢谢

小智 55

很好,很简单.将此代码段添加到您输出的任何内容中:

String.format("%.0f", percentageValue)
Run Code Online (Sandbox Code Playgroud)

  • 4.6 -> 5, 3.4 -> 3 我认为它会将数字四舍五入,而不是删除句点后的数字。 (2认同)

C-O*_*tto 39

您可以将double值转换为int值. int x = (int) y其中y是你的双变量.然后,打印x不会给出小数位(15000而不是15000.0).

  • 不建议使用类型转换为int,因为你的double可能超出了int支持的范围 (45认同)
  • @AbuSulaiman你做错了. (3认同)
  • 这个答案如何?我收到一个编译错误,提示您不能将 double 转换为 int。 (2认同)
  • Nevermind @ C-Otto Doornob发现我使用的是Double而不是double.谢谢你纠正我. (2认同)

Atu*_*lic 22

我这样做是为了从double值中删除小数位

new DecimalFormat("#").format(100.0);
Run Code Online (Sandbox Code Playgroud)

以上的输出是

100


Doo*_*nob 12

你可以用

String newValue = Integer.toString((int)percentageValue);
Run Code Online (Sandbox Code Playgroud)

要么

String newValue = Double.toString(Math.floor(percentageValue));
Run Code Online (Sandbox Code Playgroud)


小智 10

你可以转换double,float变量integer在使用一个单一的代码行明确的类型转换.

float x = 3.05
int y = (int) x;
System.out.println(y);
Run Code Online (Sandbox Code Playgroud)

输出将是 3


ede*_*ora 5

我会试试这个:

String numWihoutDecimal = String.valueOf(percentageValue).split("\\.")[0];
Run Code Online (Sandbox Code Playgroud)

我已经测试了它并且它可以工作,所以它只是从这个字符串转换为任何类型的数字或你想要的任何变量.你可以这样做.

int num = Integer.parseInt(String.valueOf(percentageValue).split("\\.")[0]);
Run Code Online (Sandbox Code Playgroud)

  • String.valueOf不可取,因为你的double可以用指数/标识符表示,例如,9.99999E11 (3认同)

Rag*_*dra 5

尝试一下,您将从 format 方法中获得一个字符串。

DecimalFormat df = new DecimalFormat("##0");

df.format((Math.round(doubleValue * 100.0) / 100.0));
Run Code Online (Sandbox Code Playgroud)


小智 5

Double d = 1000d;
System.out.println("Normal value :"+d);
System.out.println("Without decimal points :"+d.longValue());
Run Code Online (Sandbox Code Playgroud)