简体   繁体   中英

How to convert big floats to int

I wrote a program in java and php . In which a loop runs 64 times. And keep adding n to n :

Java Code:

  public static void main(String[] args) {
    double n = 1;
    double p = 1;
    for(int i = 1;i <= 64;i++){
        n = n + n;
        p = p + n;
    }
    System.out.println(p);
}

PHP code:

<?php
    $n = 1;
    $p = 0;
    for($i = 1;$i <= 64;$i++){
        $n = $n + $n;
        $p = $p + $n;
    }
    echo($p);

?>

And the output of both of these is:

3.6893488147419E+19

Now I want to know is it possible to convert this big float to int? if yes, Then how. In both languages.

I would use the BigInteger type,

public static void main(String[] args) {
    BigInteger n = BigInteger.ONE;
    BigInteger p = BigInteger.ONE;
    for(int i = 1;i <= 64;i++){
        n = n.add(n);
        p = p.add(n);
    }
    System.out.println(p);
}

Output is

36893488147419103231

Edit Based on your comment, you really wanted something more like The Legend of the Chessboard -

BigInteger n = BigInteger.ONE;
BigInteger p = BigInteger.ZERO;
BigInteger TWO = new BigInteger("2");
for (int i = 1; i <= 64; i++) {
    StringBuilder sb = new StringBuilder();
    sb.append("For square #: " + i);
    sb.append(", Grains on square: " + n);
    p = p.add(n);
    n = n.multiply(TWO);
    sb.append(", Running Total: " + p);
    System.out.println(sb.toString());
}

The number is too large to fit in a long . To get the closest integral approximation, convert the double to a BigInteger by way of a BigDecimal :

BigDecimal bd = BigDecimal.valueOf(p);
BigInteger bi = bd.toBigInteger();

However, to get an exact result, perform all the calculations using BigIntegers:

import static java.math.BigInteger.ONE;

BigInteger n = ONE;
BigInteger p = ONE;
for (int i = 1; i <= 64; i++) {
    n = n.add(n);
    p = p.add(n);
}
System.out.println(p);

The difference between the approximate and exact values is:

36893488147419103000
36893488147419103231

Java:Math.round(float),PHP:round(value,precision)但是你会精确

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM