我有任何未签名的long值。我要做的就是将它放在双精度点(以十进制表示)之后,如下所示:


  myLong = 1024
  dotLong = 0.1024


我可以在编写扫描仪时根据扫描的位数进行操作。

private long scanDecDigits()
{
    int digIndex = 0;
    char ch;

    while (input.remains())
    {
        ch = input.get();

        if (!AS3Char.isDecDigit(ch))
            break;

        // Push up to 10 digits; ignore rest.
        if (i < 10)
            numDigits[digIndex++] = ch - '0';
    }

    decBase = Math.pow(10, digIndex);

    long sub = decBase;
    long value = 0;

    for (digIndex = 0; sub != 0; sub /= 10)
        value += numDigits[digIndex++] * sub;

    return value;
}


另外,这也可以:

public class Main
{
    public static void main(String[] args)
    {
        System.out.println(putInDecimal(255));
    }

    public static double putInDecimal(long lv)
    {
        return ((double) lv) / ((double) tenPow(lv));
    }

    public static long tenPow(long lv)
    {
        return (lv < 10)  ? 10 :
               (lv < 100) ? 100 :
               (lv < 1e3) ? (long) 1e3 :
               (lv < 1e4) ? (long) 1e4 :
               (lv < 1e5) ? (long) 1e5 :
               (lv < 1e6) ? (long) 1e6 :
               (lv < 1e7) ? (long) 1e7 :
               (lv < 1e8) ? (long) 1e8 :
                            (long) 1e9;
    }
}


提示。

最佳答案

最简单,最清晰的解决方案是(如上所述):

return Double.parseDouble("0."+lv);


更多数学解决方案:

return lv / Math.pow(10, Math.ceil(Math.log10(lv + 1)));


两者都只适用于非负值。如果您需要管理负数,这应该可以:

return lv / Math.pow(10, Math.ceil(Math.log10(Math.abs(lv) + 1)));

关于java - 在Java中将整数有效地放在小数点后,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47112640/

10-12 00:33
查看更多