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
36
If you do not understand, feel free to ask questions.
You can multiply by 100 and use Math.floor(double) , e.g.
100
Math.floor(double)
int y = (int) Math.floor(x * 100); System.out.println(y);
I get (requested)
Please note that if you use float , you will get 36.0 .
float
36.0
You can multiply x by 100 and use int instead of float. I tried the code below:
x
int
double x = 0.36843871; int y = (int)(x*100); System.out.println(y);
And I got a conclusion like:
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 );
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.
Source: https://habr.com/ru/post/1238691/More articles:Why does "transform-es2015-modules-commonjs" add "use strict" in Babel 6? - babeljsHow to use rxandroid to listen to gps location update - androidLogical errors, winner check in Tic Tac Toe - c ++Replace user element with template itself (and not include it in user element) in Aurelia? - javascriptHow is a pointer to a member function implemented in C ++? - c ++Protocol buffers, where to use them? - pythonHow to make a protocol extension restriction for two types in Swift - iosAllow encryption of certificate modulo .io - sslJsoup cancels special characters - htmlStrange case of overriding a static method in java - javaAll Articles