Java gets the first 2 decimal digits of double

I have a huge double that I want to get from the first two decimal digits as a float. Here is an example:

double x = 0.36843871 float y = magicFunction(x) print(y) 

Output: 36

If you do not understand, feel free to ask questions.

+5
source share
4 answers

You can multiply by 100 and use Math.floor(double) , e.g.

 int y = (int) Math.floor(x * 100); System.out.println(y); 

I get (requested)

 36 

Please note that if you use float , you will get 36.0 .

+6
source

You can multiply x by 100 and use int instead of float. I tried the code below:

 double x = 0.36843871; int y = (int)(x*100); System.out.println(y); 

And I got a conclusion like:

 36 
+3
source

In case x is greater than 1 and negative:

  double x = -31.2232; double xAbs = Math.abs( x ); String answer = ""; if( ( int )xAbs == 0 ) { answer = "00"; } else { int xLog10 = ( int )Math.log10( xAbs ); double point0 = xAbs / Math.pow( 10, xLog10 + 1 ); // to 0.xx format answer = "" + ( int )( point0 * 100 ); } System.out.println( answer ); 
+2
source

For the correct handling of a negative flag and all ranges:

 double y = Math.abs(x); while (y < 100) y *= 10; while (y > 100) y /= 10; return (float)(int)y; 

You also need to handle null correctly, not show.

+2
source

Source: https://habr.com/ru/post/1238691/


All Articles