Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change 0.xxxx to xxxx in Java

Tags:

java

math

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 precision 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.

like image 873
ommar Avatar asked Jul 29 '10 02:07

ommar


3 Answers

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());
like image 134
Eugene Ryzhikov Avatar answered Sep 23 '22 08:09

Eugene Ryzhikov


Multiply by 10 until trunc x = x.

Something like (untested code):

double val = ... ; // set the value.

while(Math.floor(val) != val)
    val *= 10.0;
like image 39
Charlie Martin Avatar answered Sep 21 '22 08:09

Charlie Martin


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.)

like image 28
Amber Avatar answered Sep 22 '22 08:09

Amber