# Parsing Decimal values from JSON

**URL:** <https://forums.swift.org/t/parsing-decimal-values-from-json/6906>\
**Category:** Using Swift\
**Created:** [October 28, 2017, 6:23pm UTC](https://forums.swift.org/t/parsing-decimal-values-from-json/6906 "2017-10-28T18:23:00Z")\
**Posts on this page:** 1\
**Showing post:** 10

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [January 21, 2018, 7:26pm UTC](https://forums.swift.org/t/parsing-decimal-values-from-json/6906/10 "2018-01-21T19:26:37Z")

</div>

With regard to your initial question about JSON. You're correct that, when you are working with currency, you really must use decimal types. However, the JSON standard does not guarantee any particular way of parsing numbers or any precision. Moreover, there is no guarantee that the value you see in a JSON file wasn't serialized from a `Double` to begin with.

So if you have no control over the data from the external service, this is not a solvable problem here because it's not a problem with how Swift parses JSON. It is entirely acceptable to the JSON standard to conclude that, in general, any floating-point value in a JSON file is more likely to be a serialized `Double` than a serialized decimal value. If you did have control over the data, serializing as a string is the most reliable way to ensure the right precision when you parse JSON.

* * *

As to @skagedal's point, I'll refer you to an earlier thread about conversion from Double to Decimal:

> [@FloatingPoint does not conform to ExpressibleByFloatLiteral](https://forums.swift.org/t/floatingpoint-does-not-conform-to-expressiblebyfloatliteral/7433):
>
> Currently, the FloatingPoint protocol does not conform to ExpressibleByFloatLiteral, whereas BinaryFloatingPoint does. The only explanation I can find for this is a brief comment from Steve Canon \<[https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160425/015691.html&gt](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160425/015691.html&gt); during the review of SE-0067 (Enhanced Floating Point Protocols) \<[https://github.com/apple/swift-evolution/blob/master/proposals/0067-floating-point-protocols.md&gt](https://github.com/apple/swift-evolution/blob/master/proposals/0067-floating-point-protocols.md&gt); : Any reason why FloatLiteralConvertible …

As I wrote there, the behavior you see is understandably surprising but actually what the semantics of `ExpressibleByFloatLiteral` demand. Technically, `3.133` is a literal that represents a _binary_ floating-point value, rounded to some precision. There is no literal in Swift for a decimal value. To get there from here is nontrivial, but it's not the primary issue with JSON that was the original question.

---

_[View the full topic](https://forums.swift.org/t/parsing-decimal-values-from-json/6906)._
