Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a long and preserve precision when printing

How do I preserve precision in my sum output. I think that what is happening is that the precision is exactly the same, but one option chooses to round.

public class Main {
    public static void main(String[] args) {
        final long seconds = 1637208584L;
        final long micro_of_second = 795307;
        final long sum = seconds + micro_of_second;
        System.out.println("seconds + micro_of_second: " + seconds + micro_of_second);
        System.out.println("sum:                       " + sum);
        System.out.println("equal?:                    " + (sum == seconds + micro_of_second));
    }
}

Output

seconds + micro_of_second: 1637208584795307
sum:                       1638003891
equal?:                    true

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue here isn’t with precision its with the line

System.out.println("seconds + micro_of_second: " + seconds + micro_of_second);

this line implicitly converts seconds and micro_of_second to a string and concatenates them together.

so the result you are seeing is actually:

"seconds + micro_of_second: " + "1637208584" + "795307"

what you want to do is evaluate the integer addition before adding it to the string. you can accomplish this by changing that line to

System.out.println("seconds + micro_of_second: " + (seconds + micro_of_second));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading