tomekowal
I am working with an API that provides currency conversion rates in JSON like this:
{
"fx_rate": 1.01
}
When reading from that API, I get a map %{"fx_rate" => 1.01} and as far as I understand I immediately lose precision because I convert the literal representation of “1.01” to float 1.01 which might not be the same internally.
I’d like to make sure that Jason does not parse this 1.01 to float but instead returns it as string %{"fx_rate" => "1.01"}. Then I have exact representation and can use Decimal.new to make further computations.
Is there a way to advise Jason to treat that field as string?
I was thinking about making a plug that changes the request body still represented as a string. It would find the "fx_rate": 1.01, and change it to "fx_rate": "1.01" with a regular expression, so that Jason can later do its job.
But I figured I will ask here first, if you have less hacky ideas ![]()
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #blog-post
- #ai
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 5- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
kartheek
If you want precision in decimals, you can use fixed point arithmetic.
Simple idea - represent everything in integers - multiply everything by 10 n where n is the number of precision digits .
This technique is used in finance, gaming, graphics, etc
adamu
Have you seen the
floats: :decimalsoption toJason.decode/2? That might be what you’re looking for.Edit: For Plug, that looks like this:
Sebb
There is the
floats: decimaloption, but out of curiosity, would it ever really be a problem if you just useFloat.to_string.While “The closest representable number to 0.1 is 0.1000000014” it is still converted to
0.1tomekowal
Thank you guys! I missed the floats: :decimal!
adamu
This plug example has now been added to the docs.