Java 获取双精度数的前 2 位小数
Java get first 2 decimal digits of a double
我有一个巨大的双精度数,我想从中获取前两位十进制数字作为浮点数。这是一个例子:
double x = 0.36843871
float y = magicFunction(x)
print(y)
输出:36
如有不明白欢迎提问。
您可以乘以 100
并像
一样使用 Math.floor(double)
int y = (int) Math.floor(x * 100);
System.out.println(y);
我得到(请求的)
36
请注意,如果您使用 float
,那么您将得到 36.0
。
您可以将 x
乘以 100 并使用 int
而不是浮点数。我尝试了以下代码:
double x = 0.36843871;
int y = (int)(x*100);
System.out.println(y);
得到的输出为:
36
如果 x 大于 1 且为负数:
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 );
要正确处理否定案例和所有范围:
double y = Math.abs(x);
while (y < 100)
y *= 10;
while (y > 100)
y /= 10;
return (float)(int)y;
您还需要正确处理零,未显示。
我有一个巨大的双精度数,我想从中获取前两位十进制数字作为浮点数。这是一个例子:
double x = 0.36843871
float y = magicFunction(x)
print(y)
输出:36
如有不明白欢迎提问。
您可以乘以 100
并像
Math.floor(double)
int y = (int) Math.floor(x * 100);
System.out.println(y);
我得到(请求的)
36
请注意,如果您使用 float
,那么您将得到 36.0
。
您可以将 x
乘以 100 并使用 int
而不是浮点数。我尝试了以下代码:
double x = 0.36843871;
int y = (int)(x*100);
System.out.println(y);
得到的输出为:
36
如果 x 大于 1 且为负数:
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 );
要正确处理否定案例和所有范围:
double y = Math.abs(x);
while (y < 100)
y *= 10;
while (y > 100)
y /= 10;
return (float)(int)y;
您还需要正确处理零,未显示。