How to change 0.xxxx to xxxx in Java
As mentioned above. I give one example, let's say all the test values are less than 1 but greater than 0.
- 0.12 (precision: 3, scale:2)
- 0.345 (precision: 4, scale:3)
- 0.6789 (precision: 5, scale:4)
how do i convert those value without hard-coding the scale and pr开发者_开发知识库ecision value.
- 0.12 -> 12
- 0.345 -> 345
- 0.6789 -> 6789
for 0.1 and 0.01 and 0.001 should get 1 (i know this i bad idea but i have been given sets of business rules of the software)
i prefer solution in java but if there is a math algorithm it is better. thanks.
The solution is much simpler then anybody presented here. You should use BigDecimal:
BigDecimal a = new BigDecimal("0.0000012");
BigDecimal b = a.movePointRight(a.scale());
Multiply by 10 until trunc x = x.
Something like (untested code):
double val = ... ; // set the value.
while(Math.floor(val) != val)
val *= 10.0;
One option would be to simply convert to string, split on the decimal point, and grab the portion after it back into an integer:
Integer.parseInt((Double.toString(input_val).split('\\.'))[1])
(Note: you may want to do some error checking as part of the process; the above example code is a condensed version just designed to convey the point.)
Improving Amber's idea:
//for 0 <= x < 1
Integer.parseInt((Double.toString(x).replaceFirst("0.", ""));
It works well from any value below 1. Any value 1 and above will trigger java.lang.NumberFormatException
Edit: Can someone tell me the difference if the data is like below?
0.0012 -> 12
0.12 -> 12
Are you trying something like this?
public static void main(String[] args) {
double d = 0.1234;
while(d>(long)d){
d*=10;
}
System.out.println((long)d);
}
精彩评论