Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
Data type for nanosecond time precision in Java

I would like to have a numeric variable that contains integer number with nanosecond precision. I tried this:

Instant t = Instant.now();
a = BigDecimal.valueof(t.getEpochSecond() * 1e9 + t.getNano());
b = BigDecimal.valueof(t.getEpochSecond() * 1e9 + t.getNano() + 1);

Both a and b are contains same value (e.g. 1.60681511777265408E+18), the +1 operation is lost here.

Any idea how to deal with this precision? The goal of it is to keep nanosecond-precision timestamp for time column in InfluxDB. I understand it has something to do with double precision (Java BigDecimal difference), but I haven't found any working solution yet.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Just do the operations with the methods in BigDecimal. And make sure you don't use valueOf(double). You can use valueOf(long), however.

BigDecimal a = BigDecimal.valueOf(t.getEpochSecond())
            .multiply(BigDecimal.valueOf(1_000_000_000))
            .add(BigDecimal.valueOf(t.getNano()));

BigDecimal b = BigDecimal.valueOf(t.getEpochSecond())
            .multiply(BigDecimal.valueOf(1_000_000_000))
            .add(BigDecimal.valueOf(t.getNano()))
            .add(BigDecimal.ONE);

Printing a and b gives something like:

1606815981554921000
1606815981554921001
over 4 years ago · Santiago Trujillo Report

0

If you're storing an integer value, why use a BigDecimal instead of a BigInteger?

import java.time.*;
import java.math.*;

public class MyClass {
    public static void main(String args[]) {
      Instant t = Instant.now();
      BigInteger a = BigInteger.valueOf(t.getEpochSecond() * 1_000_000_000
              + t.getNano());
      BigInteger b = BigInteger.valueOf(t.getEpochSecond() * 1_000_000_000
              + t.getNano() + 1);

      System.out.println(a); // 1606816120696314000
      System.out.println(b); // 1606816120696314001
    }
}

Need to switch to BigInteger math methods in the year 2262 though, because the long argument will start overflowing.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!