Created
March 13, 2025 21:34
-
-
Save karenpayneoregon/0a39a0115f5bc63659f92e1436a2e5aa to your computer and use it in GitHub Desktop.
Serialize decimals to 2 places
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Provides a custom JSON converter for <see cref="decimal"/> values, ensuring consistent formatting and parsing. | |
/// </summary> | |
/// <remarks> | |
/// This converter reads <see cref="decimal"/> values from JSON as strings and parses them using | |
/// <see cref="CultureInfo.InvariantCulture"/>. When writing, it formats <see cref="decimal"/> values | |
/// as strings with two decimal places using the same culture. | |
/// </remarks> | |
public class FixedDecimalJsonConverter : JsonConverter<decimal> | |
{ | |
public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
{ | |
string? stringValue = reader.GetString(); | |
return string.IsNullOrWhiteSpace(stringValue) | |
? 0 | |
: decimal.Parse(stringValue, CultureInfo.InvariantCulture); | |
} | |
public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options) | |
{ | |
string numberAsString = value.ToString("F2", CultureInfo.InvariantCulture); | |
writer.WriteStringValue(numberAsString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment