How to change 0.xxxx to xxxx in Java

As mentioned above. I will give one example: let all test values ​​be less than 1, but greater than 0.

  • 0.12 (accuracy: 3, scale: 2)
  • 0.345 (accuracy: 4, scale: 3)
  • 0.6789 (accuracy: 5, scale: 4)

how to convert these values ​​without hard coding of 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 bad idea, but I was given sets of business software rules )

I prefer the solution in java, but if there is a mathematical algorithm, it is better. thanks.

+7
java math
source share
5 answers

The solution is much simpler than any presented here. You should use BigDecimal:

BigDecimal a = new BigDecimal("0.0000012"); BigDecimal b = a.movePointRight(a.scale()); 
+11
source share

Multiply by 10 until trunc x = x.

Something like (unverified code):

 double val = ... ; // set the value. while(Math.floor(val) != val) val *= 10.0; 
+4
source share

One option is to simply convert to a string, split into a decimal point, and capture the part after it returns to an integer:

 Integer.parseInt((Double.toString(input_val).split('\\.'))[1]) 

(Note: you can do some error checking as part of the process, the above sample code is a condensed version designed to transmit a point.)

+3
source share

Improving the idea of ​​amber:

 //for 0 <= x < 1 Integer.parseInt((Double.toString(x).replaceFirst("0.", "")); 

It works fine from any value below 1. Any value of 1 and above raises a java.lang.NumberFormatException

Edit: can someone tell me the difference if the data is similar below?

 0.0012 -> 12 0.12 -> 12 
0
source share

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); } 
0
source share

All Articles