E
E
Elena2021-02-05 22:08:21
Java
Elena, 2021-02-05 22:08:21

How to calculate the sum of real numbers?

How to calculate the sum of all real numbers, discarding the real part?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-02-05
Hasanly @azerphoenix

Here are code examples:

public class Main {

  public static void main(String[] args) {

    final double num1 = 10.14;
    final double num2 = 11.142;
    final double num3 = 13.1844;
    final Double sum = (num1 + num2 + num3);

    long result1 = Math.round(sum);
    System.out.println(result1);

    BigDecimal result2 = BigDecimal.valueOf(sum).setScale(0, RoundingMode.HALF_UP);
    System.out.println(result2);

    BigDecimal result3 = BigDecimal.valueOf(sum).round(new MathContext(2, RoundingMode.HALF_UP));
    System.out.println(result3);

    Long result4 = sum.longValue();
    System.out.println(result4);
    
  }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question