Dispenser/DispenserUI/ViewModels/Converter/DoubleToPrecisionConverter.cs

38 lines
1.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Globalization;
using Avalonia.Data.Converters;
namespace DispenserUI.ViewModels.Converter;
/// <summary>
/// 对象的数值转换为指定精度的字符串
/// </summary>
public class DoubleToPrecisionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int digits = 3;
if (int.TryParse(parameter as string, out int _digits))
{
digits = _digits;
}
return value switch
{
// 确保输入值是浮点数
int => value,
double val => Math.Round(val, digits),
_ => value
};
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// 从字符串转换回浮点数
if (value is string stringValue && double.TryParse(stringValue, out var result)) return result;
// 如果转换失败则返回0
return 0d;
}
}