Link to home
Start Free TrialLog in
Avatar of jtran007
jtran007

asked on

c# display timespan in 2 digits after decimal

Hi,
I got the elapse time from stopwatch, I'd like to display the elaspe time
in 2 digits after decimal point. What format I should use?
Thanks,
JT
Avatar of s_chilkury
s_chilkury
Flag of United States of America image

Try the following:
string timeElapsed =  String.Format("{0} Hours, {1} Minutes, {2} Seconds", Math.Floor(duration.TotalHours), Math.Floor(duration.TotalMinutes), Math.Floor(duration.TotalSeconds);
String.Format("{0:0.##}", 123.4567);      // "123.46"
ASKER CERTIFIED SOLUTION
Avatar of Sudhakar Pulivarthi
Sudhakar Pulivarthi
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jdavistx
jdavistx

There's several ways you could do this, but here's the ones that jump to mind:

var sw = new Stopwatch();

sw.Start();
System.Threading.Thread.Sleep(1000);
sw.Stop();

Console.WriteLine(sw.Elapsed.TotalMilliseconds.ToString("N2"));
Console.WriteLine(Math.Round(sw.Elapsed.TotalMilliseconds, 2));
Console.WriteLine(String.Format("{0:0.00}", sw.Elapsed.TotalMilliseconds));

Open in new window

Avatar of jtran007

ASKER

Hi naman,

I use :
           MessageBox.Show("Time elapse: Min,Secs" + String.Format("{0:0.##}", ts.TotalMinutes.ToString()) + "," + String.Format("{0:0.##}", ts.TotalSeconds.ToString()));

But it is nor working.
Regards,
JT
Don't call "ToString()" on TotalMinutes.
...  or TotalSeconds    : )
Thanks,
JT