-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Konrad Jamrozik
committed
Jun 29, 2024
1 parent
d232854
commit 8953554
Showing
4 changed files
with
57 additions
and
21 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
using System; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace Lib.Json; | ||
|
||
public class DoubleDecimalConverter : JsonConverter<double> | ||
{ | ||
private readonly int _decimalPlaces; | ||
|
||
public DoubleDecimalConverter(int decimalPlaces) | ||
{ | ||
if (decimalPlaces < 0) | ||
{ | ||
throw new ArgumentException($"Decimal places ({decimalPlaces}) must be non-negative."); | ||
} | ||
_decimalPlaces = decimalPlaces; | ||
} | ||
|
||
public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
return reader.GetDouble(); | ||
} | ||
|
||
public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options) | ||
{ | ||
// Limit the number of decimal places | ||
double roundedValue = Math.Round(value, _decimalPlaces); | ||
writer.WriteNumberValue(roundedValue); | ||
} | ||
} |