using System; using System.Globalization; using Avalonia.Data.Converters; namespace DispenserUI.ViewModels.Converter; /// /// 对象的数值转换为指定精度的字符串 /// 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; } }