[英]Java get first 2 decimal digits of a double
我有一个巨大的双倍,我希望得到前2个十进制数字作为浮点数。 这是一个例子:
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
而不是float。 我尝试了下面的代码:
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;
您还需要正确处理零,而不是显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.