Decimal property editor: Flexibly parse decimal value with different separators (closes #20823) (#20828)

* Flexibly parse decimal value with different separators.

* Applied suggestions from code review.
This commit is contained in:
Andy Butland
2025-11-14 02:20:12 +01:00
committed by GitHub
parent 73847d1eff
commit a4438e5b21
2 changed files with 53 additions and 3 deletions

View File

@@ -37,7 +37,6 @@ public class DecimalPropertyEditor : DataEditor
/// <inheritdoc />
protected override IConfigurationEditor CreateConfigurationEditor() => new DecimalConfigurationEditor();
/// <summary>
/// Defines the value editor for the decimal property editor.
/// </summary>
@@ -109,7 +108,38 @@ public class DecimalPropertyEditor : DataEditor
/// <inheritdoc/>
protected override bool TryParsePropertyValue(object? value, out double parsedDecimalValue)
=> double.TryParse(value?.ToString(), CultureInfo.InvariantCulture, out parsedDecimalValue);
{
if (value is null)
{
parsedDecimalValue = default;
return false;
}
if (value is decimal decimalValue)
{
parsedDecimalValue = (double)decimalValue;
return true;
}
if (value is double doubleValue)
{
parsedDecimalValue = doubleValue;
return true;
}
if (value is float floatValue)
{
parsedDecimalValue = (double)floatValue;
return true;
}
if (value is IFormattable formattableValue)
{
return double.TryParse(formattableValue.ToString(null, CultureInfo.InvariantCulture), NumberStyles.Any, CultureInfo.InvariantCulture, out parsedDecimalValue);
}
return double.TryParse(value.ToString(), NumberStyles.Any, CultureInfo.CurrentCulture, out parsedDecimalValue);
}
}
/// <summary>

View File

@@ -161,7 +161,27 @@ public class DecimalPropertyValueEditorTests
Assert.AreEqual(1, result.Count());
var validationResult = result.First();
Assert.AreEqual(validationResult.ErrorMessage, "validation_outOfRangeMaximum");
Assert.AreEqual("validation_outOfRangeMaximum", validationResult.ErrorMessage);
}
}
[TestCase(1.8, true)]
[TestCase(2.2, false)]
[SetCulture("it-IT")] // Uses "," as the decimal separator.
public void Validates_Is_Less_Than_Or_Equal_To_Configured_Max_With_Comma_Decimal_Separator(object value, bool expectedSuccess)
{
var editor = CreateValueEditor(min: 1, max: 2);
var result = editor.Validate(value, false, null, PropertyValidationContext.Empty());
if (expectedSuccess)
{
Assert.IsEmpty(result);
}
else
{
Assert.AreEqual(1, result.Count());
var validationResult = result.First();
Assert.AreEqual("validation_outOfRangeMaximum", validationResult.ErrorMessage);
}
}