Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Working With Numbers Numbers and Strings

Stefan Cutajar
Stefan Cutajar
7,747 Points

converting to hours

Hi , I know this maybe out of subject but was wondering if you want to add time together like 2.25hrs + 8.40hrs that will add up to 10.65. Is it possible to make the decimal start another number after .60? Thanks

2 Answers

Steven Parker
Steven Parker
229,732 Points

Floating math doesn't work like that, but you could rescale the fractional part to become actual decimal hours, do the math and then scale it back for display:

var hours = d => Math.trunc(d) + (d - Math.trunc(d)) * 5 / 3;  // convert to decimal hours
var homin = h => Math.trunc(h) + (h - Math.trunc(h)) * 3 / 5;  // convert to hours.minutes
console.log(homin(hours(2.25) + hours(8.40)));                 // shows 11.05

Also, JavaScript has a "Date" object that stores and manipulates time and date as a number of milliseconds:

var showTime = t => `${t.getHours()}:${('0' + t.getMinutes()).slice(-2)}`;
var start = new Date();                                         // start with the current date & time
start.setHours(2, 25, 0, 0);                                    // set specific time
console.log(showTime(start));                                   // shows "2:25"
var then = new Date(start.getTime() + ((8 * 60) + 30) * 60000); // add 8 hours and 30 minutes (in ms)
console.log(showTime(then));                                    // shows "10:05"

Here's a short tutorial on date and time.

Stefan Cutajar
Stefan Cutajar
7,747 Points

Thanks for your time. Looks like I need a bit more experience so I can understand this better