Ethan
Ethan

Reputation: 628

Binding ComboBox SelectedItem to double

My ComboBox's ItemsSource is binding to a List<double> options and the SelectedItem is binding to a property double SelectedOption.

If options contains the values 0.0060F, 0.0075F, 0.0100F and SelectedItem = 0.0060F, the ComboBox does should, but does not, reflect this. Instead, selecting the ComboBox shows the options list items with their strange decimal representations. Is it even possible to do data binding on variables of type double with their unpredictable representation?

Code

ViewModel:

//Properties
public List<double> Options{get;set;}
public double SelectedOption{get;set;}

//Constructor
public ViewModel()
{
    Options =  new List<double>();
    Options.Add(0.0060F);
    Options.Add(0.0075F);
    Options.Add(0.0100F);

    SelectedOption = 0.0060F;
}

Binding:

<ComboBox ItemsSource="{Binding Path=Options}" 
    SelectedItem="{Binding Path=SelectedOption, Mode=TwoWay}" />

The options that are shown in the ComboBox are:

Upvotes: 0

Views: 2380

Answers (1)

Elias Platek
Elias Platek

Reputation: 1114

Maybe you should give a read at what floating points are: http://csharpindepth.com/Articles/General/FloatingPoint.aspx

Those values are used to give a as close as possible to reality representation of numbers. If you want exact values, use System.Decimal

Upvotes: 2

Related Questions