Daniel Ellison
Daniel Ellison

Reputation: 1349

Moment JS - Round up hours and limiting output to 2 decimals

Can't seem to find information about how to round up the result of my hours results. Looking only limiting the output to 2 decimals.

For example, the console.log below will provide me with 1.4166666666666667 but I would like if it would round up to 1.47 (maximum of 2 decimals).

var startTime = $('2016-02-21 18:00');
var endTime = $('2016-02-21 19:25');
var duration = moment.duration(moment(endTime, 'YYYY/MM/DD HH:mm').diff(moment(startTime, 'YYYY/MM/DD HH:mm')));
var hours = duration.asHours()
console.log(hours); 

Would anyone know if this is possible using moment JS? I created an example of this script here https://jsfiddle.net/ewmq6sof/1/ if that would help.

Upvotes: 2

Views: 3544

Answers (1)

baao
baao

Reputation: 73251

The easiest thing to do is to just use .toFixed(2)

var hours = duration.asHours().toFixed(2)

If you always want to decimals, or use Math.round()

var hours = Math.round(duration.asHours() * 100) / 100

if you want a maximum of two decimals.

No need for moment here.

Upvotes: 4

Related Questions