如何从double获取整数的小数部分?

问题描述 投票:3回答:5

如何将double分成两个整数?小数点前的第一个数字和第二个数字。例如:

            double doub = 543.345671;
            int num1 = (int) doub; //543
            int num2 = getNumAfterDecimal(doub-num1); //return 345671

我需要小数部分到整数。

java math decimal decimal-point
5个回答
2
投票

这取决于小数点后你想要多少位数,但这是要点:

double d = doub - (int)doub; // will give you 0.xyz
int result = d * 1000; // this is for 3 digits, the number of zeros in the multiplier decides the number of digits 

3
投票

使用qazxsw poi将qazxsw poi映射到qazxsw poi:qazxsw poi然后使用Double.toString()获得不同的部分作为doubles。然后,可选地,String将这些值解析为Double.toString(doub)s:

String.split("\\.")

输出:

String

2
投票

我看,

Integer.valueOf()

2
投票

使用正则表达式拆分获取它,

Integer

打印,

double doub = 543.345671;
// Here, you want to split the String on character '.'
// As String.split() takes a regex, the dot must be escaped. 
String[] parts = Double.toString(doub).split("\\.");
System.out.println(Integer.valueOf(parts[0]));
System.out.println(Integer.valueOf(parts[1]));

1
投票

这就是我需要的。谢谢,Nir Levy!但有时候舍入错误是可能的。

543
345671

我添加了Math.round()来正确获取小数部分。

Double d=543.345671;
String line=String.valueOf(d);
String[] n=line.split("\\.");
int num1=Integer.parseInt(n[0]);
int num2=Integer.parseInt(n[1]);
© www.soinside.com 2019 - 2024. All rights reserved.