Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created March 13, 2025 21:34
Show Gist options
  • Save karenpayneoregon/0a39a0115f5bc63659f92e1436a2e5aa to your computer and use it in GitHub Desktop.
Save karenpayneoregon/0a39a0115f5bc63659f92e1436a2e5aa to your computer and use it in GitHub Desktop.
Serialize decimals to 2 places
/// <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