Project

General

Profile

Actions

Bug #19686

closed

BigDecimal object returns JSON string

Bug #19686: BigDecimal object returns JSON string

Added by goh (Goh Matsumoto) over 2 years ago. Updated over 2 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-darwin21]
[ruby-dev:<unknown>]

Description

Hi,

When I call the to_json method to the BigDecimal object, it returns a JSON string.
Is this intentional?

> ruby -v -rbigdecimal -rjson -e 'p BigDecimal("1.2").to_json'
ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-darwin21]
"\"0.12e1\""
> ruby -v -rjson/add/bigdecimal -e 'p BigDecimal("1.2").to_json'
ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-darwin21]
"{\"json_class\":\"BigDecimal\",\"b\":\"18:0.12e1\"}"

I expect a JSON number like "0.12e1".

Updated by byroot (Jean Boussier) over 2 years ago Actions #1

  • Status changed from Open to Closed

I believe it's intentional as the main point of BigDecimal is to avoid float imprecision issues.

On a tangent, this issue should have been filed in JSON's bug tracker: https://github.com/flori/json/issues, But anyway, changing this would break way too much code so unlikely to happen.

Updated by byroot (Jean Boussier) over 2 years ago Actions #2

Forgot to say that to fix your issue you can convert BigDecimal with to_f prior to calling to_json.

Actions

Also available in: PDF Atom