如何在Java中将双数字分成两个十进制数?
问题描述:
尝试按点将两个数字分成两个小数部分。像这样:1.9分为1分和9分; 0.16分为0和16;
Trying to split a double number into two decimal parts by dot. Like this: 1.9 into 1 and 9; 0.16 into 0 and 16;
这是我的工作,但似乎有点多余,最好的方法是什么?
Here's what I do, but seems a little redundant, what's the best way to do this?
原始数字将始终为Just 0.x或1.x或0.xx或1.xx且xx> 10
The origin number will always be like Just 0.x or 1.x or 0.xx or 1.xx and xx > 10
double d = 1.9;
int a, b;
String dString = Double.toString(d);
String aString = dString.substring(0, 1);
String bString = dString.substring(2);
a = Integer.parseInt(aString);
b = Integer.parseInt(bString);
我这样做的方式似乎使用了很多String转换,我认为这不是很有效。
My way of doing this seems using to much String conversion,which I don't think is very efficient.
答
你也可以尝试这种方式
double val=1.9;
String[] arr=String.valueOf(val).split("\\.");
int[] intArr=new int[2];
intArr[0]=Integer.parseInt(arr[0]); // 1
intArr[1]=Integer.parseInt(arr[1]); // 9