Malcolm
Malcolm

Reputation: 1807

StringFormat Double without rounding

double d = toDateTime.SelectedDateTime.Subtract(
              servicefromDateTime.SelectedDateTime).TotalHours;             
string s = String.Format("{0:0}",d); 

But the String.Format rounds up the value: if d is 22.91 the String.Format gives the rounding result of 23. I don't want to round up. For example, if d is 22.1222222, then I want 22. if d is 22.999999, then I want 22.

How can I achieve this?

Upvotes: 3

Views: 5490

Answers (3)

Chris Taylor
Chris Taylor

Reputation: 53729

You could use Math.Truncate

double d = toDateTime.SelectedDateTime.Subtract(servicefromDateTime.SelectedDateTime).TotalHours; 

string s = String.Format("{0:0}", Math.Truncate(d));

Upvotes: 5

Jamiec
Jamiec

Reputation: 136239

Then you need to Math.Floor

double d = toDateTime.SelectedDateTime.Subtract(servicefromDateTime.SelectedDateTime).TotalHours;

string s = String.Format("{0:0}",Math.Floor(d)); 

Upvotes: 2

Andy White
Andy White

Reputation: 88475

If you cast the double to an int/long it will chop off any decimal component, effectively giving you a "floor" or round-down of the double.

Upvotes: 2

Related Questions