Not a duplicate of Is floating point math broken? If you take the time to read the question, I am looking for better ways of representing these floating point number in strings.
I have a numeric up/down control, essentially a normal textbox with up down buttons next to it that stores its value as a double. I have been running into an issue when cycling up and down, when the value is (or should be) 0 or -.1, the text box displays "1.38777878078145E-16" and "-0.0999999999999999" respectively (among others) and this makes the control feel messy.
I get that the floating point precision of double means that values get truncated and absolute precision for decimals longer than the doubles precision are lost. Precise representation of the actual value of -.1d is not as important to me as it's clean representation, meaning I would like -.1d (-0.0999999999999999) to simply display as "-.1".
Do not assume by my examples that all values are within one decimal, though precision is not terribly important granularity is.
Right now I am just catching the string in my double to string converter and handling it, but is there a better way to do this?
No I cannot use decimal due to its overhead.
[ValueConversion(typeof(Double), typeof(String))]
public class DoubleToStringValueConverter : IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
string res = ((double)value).ToString(culture);
if (res == "1.38777878078145E-16") res = "0";
if (res == "-0.0999999999999999") res = "-0.1";
return res;
}
public object ConvertBack(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
string val = value as string;
double res = 0d;
double.TryParse(val, System.Globalization.NumberStyles.Float, culture, out res);
return res;
}
}