lundi 4 novembre 2019

How to convert seconds to hh:mm:ss.millisecond format c++?

I need to convert seconds in to hh:mm:ss.milliseconds and I need that this format must be respected. I mean that hours, minutes and seconds must have 2 digits and milliseconds 3 digits. For example, if seconds = 3907.1 I would to obtain 01:05:07.100

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <stdio.h>
#include <sstream>
#include <math.h>
using namespace std;

int main()
{   
    double sec_tot = 3907.1;
    double hour = sec_tot/3600; // seconds in hours
    double hour_int;
    double hour_fra = modf(hour, &hour_int );//split integer and decimal part of hours
    double minutes = hour_fra*60; // dacimal hours in minutes
    double minutes_int;
    double minutes_fra = modf(minutes, &minutes_int); // split integer and decimal part of minutes
    double seconds = minutes_fra*60; // decimal minutes in seconds
    stringstream ss;
    ss << ("%02lf", hour_int) << ":" << ("%02lf", minutes_int) << ":" << ("%02lf", seconds);
    string time_obs_def = ss.str();
    cout << time_obs_def << endl;

    return 0;
}

but the output is 1:5:7.1 Thank you.

Aucun commentaire:

Enregistrer un commentaire