Java获取双

时间:2015-12-19 04:49:29

标签: java math double

我有一个巨大的双倍,我希望得到前2个十进制数字作为浮点数。这是一个例子:

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

输出:36

如果您不明白,请随时提问。

4 个答案:

答案 0 :(得分:6)

您可以乘以100并使用Math.floor(double)之类的

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

我得到(要求的)

36

请注意,如果您使用float,则会获得36.0

答案 1 :(得分:3)

您可以将x乘以100并使用int而不是浮点数。我尝试了以下代码:

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

输出为:

36

答案 2 :(得分:2)

如果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 );

答案 3 :(得分:2)

正确处理否定案例和所有范围:

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

您还需要正确处理零,而不是显示。