CRAIG
CRAIG

Reputation: 1029

Use Javascript to change a decimal to a whole number

If I have some JS:

 var ct = 1.30;

or it could also be:

 var ct = 0.04;

or it could also be:

 var ct = 4.45677;

How can I simply change these decimals to whole numbers? i.e.:

 30

for the first one

 4

for the second one and

 46

for the 3rd one?

Is there a JS method I can use to do this?

Here is the code I am working with so far. This works fine for seconds, minutes and hours, but I am left without the frames, which is why I started the process in the first place.

  var ct2 = 1.30;

  var timestamp = ct2; 
  var seconds = timestamp % 60;
 timestamp = Math.floor(timestamp / 60);
 var minutes = timestamp % 60;
 timestamp = Math.floor(timestamp / 60);
 var hours = timestamp;

This ends up giving me:

Seconds: 1

Minutes: 0

Hours: 0

But leaves me without this key part:

Frames: 30

Upvotes: 0

Views: 1192

Answers (1)

jdphenix
jdphenix

Reputation: 15425

Based on your example numbers given, this function would meet the output requirements you've given. (I'm not sure exactly what it is you're doing, so I called it foo.

var foo = function (num) { 
  num -= Math.trunc(num); 
  num *= 100; 
  return Math.round(num); 
}

Example output:

var ct1 = 0.04, 
    ct2 = 1.30,
    ct3 = 4.45677; 

console.log(foo(ct1)); 
console.log(foo(ct2));
console.log(foo(ct3)); 

>  4
>  30
>  46

Upvotes: 2

Related Questions