将字符串转换为双精度,这样我就可以按值listview进行筛选



我目前有一个名为Monthly的字符串属性,它是一个浮点计算,然后转换为字符串。一旦我所有的属性都保存了,我想用Monthly来过滤它们。通过这样做,我相信我需要将Monthly转换为double,但通过这样做我得到了一个异常,说"输入字符串的格式不正确。"下面是我的代码。。。

protected override void OnAppearing()
{
base.OnAppearing();
using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
{
conn.CreateTable<MainWindowViewModel>();
var APRS = conn.Table<MainWindowViewModel>().ToList().OrderBy(APR => Convert.ToDecimal(APR.Monthly));
APRListView.ItemsSource = APRS;

}
}

我肯定不能把它转换回字符串吗?

向模型添加只读属性以处理转换

public decimal MonthlyDecimal 
{
get 
{
try {
return Convert.ToDecimal(Monthly);
} catch (Exception ex) {
return 0;
}
}
}

至少有一个值无法转换为十进制。你可以尝试一种变通方法,比如:

protected override void OnAppearing()
{
base.OnAppearing();
using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
{
conn.CreateTable<MainWindowViewModel>();
var APRS = conn.Table<MainWindowViewModel>()
.ToList()
.OrderBy(APR => decimal.TryParse(APR.Monthly, out decimal m)?m:0);
APRListView.ItemsSource = APRS;
}
}

编辑:您可以向TryParse添加参数,以解析特定的区域性,还包括货币等的符号。

编辑:我看到你的价值中有英镑,可能表示英国的货币:

protected override void OnAppearing()
{
base.OnAppearing();
using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
{
conn.CreateTable<MainWindowViewModel>();
var APRS = conn.Table<MainWindowViewModel>()
.ToList()
.OrderBy(APR => decimal.TryParse(APR.Monthly, System.Globalization.NumberStyles.Currency, new CultureInfo("en-GB"), out decimal m)?m:0);
APRListView.ItemsSource = APRS;
}
}

首先存储并使用该值作为双精度。当您需要将其作为字符串进行显示时,可以通过在double上调用ToString轻松地将其转换为字符串,此时您可以将£添加到字符串的前面,例如:

"£" + doubleValue.ToString()

$"£{doubleValue.ToString()}"

或者,如果你需要或真的想将价值存储为以英镑开头的字符串,那么你需要在转换为双倍之前先去掉英镑,例如:

double doubleValue = Convert.ToDouble(stringValue.Replace("£", ""));

相关内容

最新更新