1

I want the end result to look like this:

"{\"price\":2.00}"

Is this possible without gsubbing the json?

No good:

{price: 2.00}.to_json
=> "{\"price\":2.0}"

Also no good:

{price: '%.2f' % 2.00}.to_json
=> "{\"price\":\"2.00\"}"
the_coder
  • 55
  • 7
  • 2
    This is a fools errand since JSON parsers doesn't give a hoot about how many decimals of 0 you're using. – max Mar 31 '21 at 16:52
  • Good to know. In that case, the first option would be preferrable then, right? – the_coder Mar 31 '21 at 16:54
  • 1
    Using an integer in the smallest currency denomination (such as cents) is prefereable if you want to avoid the rounding errors inherent in IEEE 754 double precision floats. JSON does not have a decimal number type. https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – max Mar 31 '21 at 16:56
  • 1
    If you are not performing mathematical operations on this float then just format as you see fit for viewing. If you are performing mathematical operations and have control over the data type then I would recommend following the advice provided by @max. If you are performing mathematical operations on this float and do not have control over the data type then I would recommend building an object around the parsed JSON so that you can convert this float to BigDecimal for math and from BigDecimal back to float for transmission of the JSON data. – engineersmnky Mar 31 '21 at 17:31
  • 1
    Why not keeping it as a string ? There wouldn't be any precision loss – Fravadona Mar 31 '21 at 17:42

0 Answers0