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 :
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));