-1

I have a webapi returning an amount (simplified example):

so it can return for example :

{
    Amount:40
}

{
    Amount:40.1
}

{
    Amount:40.15
}

Is it possible to return always a number with 2 decimals :

{
    Amount:40.00
}

{
    Amount:40.10
}

{
    Amount:40.15
}
Bruno
  • 4,685
  • 7
  • 54
  • 105

2 Answers2

2

You can use custom converter which rounds each decimal value to given number of fraction digits:

public class JsonDecimalConverter : JsonConverter
{
    private int decimals;

    public JsonDecimalConverter(int decimals = 2)
    {
        this.decimals = decimals;
    }

    public override bool CanConvert(Type objectType) => objectType == typeof(decimal);

    public override object ReadJson(JsonReader reader,
       Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer,
       object value, JsonSerializer serializer)
    {
        writer.WriteValue(Decimal.Round((decimal)value, decimals));
    }
}

Usage:

var thing = new Thing { Amount = 40.12345M, Name = "Foo" };
var json = JsonConvert.SerializeObject(thing, new JsonDecimalConverter());

Output:

{
  "Amount": 40.12,
  "Name": "Foo"
}

Note that this will give you 40 for decimal number 40. Because there are no meaningful digits to be stored. 40.00 is a string formatting issue which you should handle where you want to display or store this decimal representation.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • apparently @stuartd provided an example that would work even with 40: http://i.stack.imgur.com/BLz1c.png – Bruno Jun 27 '17 at 15:14
  • @ibiza well, it's a little bit surprising for me that Json NET outputs value as a number. But all you gain here is a bigger size of json. After you will consume this json and deserialize it, zeroes of `40.00` will be gone. To output those zeroes you will need to format number anyway – Sergey Berezovskiy Jun 27 '17 at 15:28
0

You simply need to use

decimal.Round(myDecimalValue, 2)
RobPethi
  • 551
  • 9
  • 27