parse long to negative number

前端 未结 7 1564
北恋
北恋 2021-01-20 14:48

code:

public class Main{
    public static void main(String[] a){
        long t=24*1000*3600;
        System.out.println(t*25);
        System.out.println(2         


        
7条回答
  •  借酒劲吻你
    2021-01-20 15:38

    If you want to do mathematical operations with large numerical values without over flowing, try the BigDecimal class.

    Let's say I want to multiply

    200,000,000 * 2,000,000,000,000,000,000L * 20,000,000

    int testValue = 200000000;
    System.out.println("After Standard Multiplication = " +
                                                           testValue * 
                                                           2000000000000000000L * 
                                                           20000000);
    

    The value of the operation will be -4176287866323730432, which is incorrect.

    By using the BigDecimal class you can eliminate the dropped bits and get the correct result.

    int testValue = 200000000;        
    System.out.println("After BigDecimal Multiplication = " +
                                  decimalValue.multiply(
                                  BigDecimal.valueOf(2000000000000000000L).multiply(
                                  BigDecimal.valueOf(testValue))));
    

    After using the BigDecimal, the multiplication returns the correct result which is

    80000000000000000000000000000000000

提交回复
热议问题