Java: Convert scientific notation to regular int

前端 未结 6 428
迷失自我
迷失自我 2020-12-06 10:23

How do I convert scientific notation to regular int For example: 1.23E2 I would like to convert it to 123

Thanks.

相关标签:
6条回答
  • 2020-12-06 10:45

    You can just cast it to int as:

    double d = 1.23E2; // or float d = 1.23E2f;
    int i = (int)d; // i is now 123
    
    0 讨论(0)
  • 2020-12-06 10:45

    You can also use something like this.

    (int) Double.parseDouble("1.23E2")
    
    0 讨论(0)
  • 2020-12-06 10:49

    Check out DecimalFormat.parse().

    Sample code:

    DecimalFormat df = new DecimalFormat();
    Number num = df.parse("1.23E2", new ParsePosition(0));
    int ans = num.intValue();
    System.out.println(ans); // This prints 123
    
    0 讨论(0)
  • 2020-12-06 10:51

    You can implement your own solution:

    String string = notation.replace(".", "").split("E")[0]
    
    0 讨论(0)
  • 2020-12-06 10:52

    I am assuming you have it as a string.

    Take a look at the DecimalFormat class. Most people use it for formatting numbers as strings, but it actually has a parse method to go the other way around! You initialize it with your pattern (see the tutorial), and then invoke parse() on the input string.

    0 讨论(0)
  • 2020-12-06 10:55

    If you have your value as a String, you could use

    int val = new BigDecimal(stringValue).intValue();
    
    0 讨论(0)
提交回复
热议问题