如何在Json.net中强制使用最少的小数位数? [英] How can I force a minimum number of decimal places in Json.net?
问题描述
当我使用json.net将小数写到json时,我变得很烦人.有时是1 dp,其他时候是2.
I'm getting an annoying inconsistency when I'm writing decimals to json using json.net. Sometimes it's to 1 dp, other times 2.
很明显,我知道将小数输出到具有一定小数位数的字符串的解决方案,例如 this ,但是如果没有编写自定义的序列化程序,您将无法使用json.net进行控制.
Obviously I'm aware of solutions to output decimals to strings with a certain number of decimals such as this, but you don't have that control using json.net without writing a custom serializer I guess.
我还知道Math.Round
强制执行最大小数位数,这个问题与强制执行最小小数位数有关.
I am also aware of Math.Round
to enforce a maximum number of decimal places, this question relates to enforcing a minimum number of decimal places.
前两个测试表明发生了什么,它保持声明或计算中的原始小数位数不变.
The first two tests show what is happening, it is keeping the original number of decimal places from the declaration or calculation.
我发现我可以添加然后减去一小部分,接下来的两个测试都可以正常工作,但是有没有更清洁的方法?
I found I can add and then subtract a small fraction which the next two tests show working, but is there a cleaner way?
[TestFixture]
public sealed class DecimalPlaces
{
public class JsonType
{
public decimal Value { get; set; }
}
[Test]
public void TwoDp()
{
var obj = new JsonType { Value = 1.00m };
Assert.AreEqual("{\"Value\":1.00}", JsonConvert.SerializeObject(obj));
}
[Test]
public void OneDp()
{
var json = new JsonType { Value = 1.0m };
Assert.AreEqual("{\"Value\":1.0}", JsonConvert.SerializeObject(obj));
}
private decimal ForceMinimumDp(decimal p, int minDecimalPlaces)
{
decimal smallFrac = 1m/((decimal)Math.Pow(10, minDecimalPlaces));
return p + smallFrac - smallFrac;
}
[Test]
public void ForceMinimumTwoDp()
{
var obj = new JsonType { Value = ForceMinimumDp(1.0m, 2) };
Assert.AreEqual("{\"Value\":1.00}", JsonConvert.SerializeObject(obj));
}
[Test]
public void ForceMinimumThreeDp()
{
var obj = new JsonType { Value = ForceMinimumDp(1.0m, 3) };
Assert.AreEqual("{\"Value\":1.000}", JsonConvert.SerializeObject(obj));
}
}
推荐答案
您可以使用自定义JSON转换器:
You can do it with a custom JSON converter:
class DecimalJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return 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.WriteRawValue(((decimal) value).ToString("F2", CultureInfo.InvariantCulture));
}
}
这是一个非常基本的转换器.您可能需要扩展它以支持其他浮点类型,甚至可能还支持整数类型.
This is a very basic converter. You may need to extend it to support other floating-point types, or perhaps even integer types too.
现在实例化序列化器并将其传递给自定义转换器,如下所示:
Now instantiate your serialiser and pass it your custom converter, like so:
var serializer = new JsonSerializer();
serializer.Converters.Add(new DecimalJsonConverter());
这篇关于如何在Json.net中强制使用最少的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!