• Post Reply Bookmark Topic Watch Topic
  • New Topic

Convert Nanoseconds into Seconds  RSS feed

 
ranua agarwal
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am using this piece of code to change nanosecond to second--



By using this i am unable to hold with precision.
Output of above program is : 1
While i want in this way : 1.56250003

Can somebody point how to achieve this?

Thanks,
Ranu.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The TimeUnit.convert() method(s) deal only in long integers; they can't represent fractions of a unit. Instead of using TimeUnit.convert(), you can just divide by 10^9 -- ie.,

System.out.println(1562500003 / 1E9);

gives the "right" answer.
 
ranua agarwal
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You Ernest.
I did it with
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ranua agarwal wrote:

Ok, that works, but why use the Long wrapper class, why not just use a primtive long directly? You just have to cast it properly to make sure you get a floating-point division, instead of an integer division.

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or turn the other operand into a double:
The added .0 turns the constant into a double, and the result of the division will be a double if at least one of the operands is a double. Of course, 1000000000.0 is the same as 1E9 which Ernest already suggested.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!