StringFormat Double Without Rounding

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

But String.Format rounds the value: if d is 22.91, String.Format gives the result of rounding 23. I do not want to round. 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?

+3
source share
3 answers

You can use Math.Truncate

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

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

If you press double on int / long, it will chop off any decimal component, effectively giving you the "gender" or rounding of the double.

+2
source

Then you need Math.Floor

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

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

Source: https://habr.com/ru/post/1745128/


All Articles