Uploaded image for project: 'Swift'
  1. Swift
  2. SR-6631

Swift JSONEncoder is dependent to the locale decimal point policy encoding

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Foundation
    • Labels:
      None
    • Environment:

      The bug is confirmed on Darwin (but should affect Linux too).

       

      Description

      When using a locale that does not use "."  as decimal separator, the JSONEncoder & JSONSerialization encodes the Double value with the localized decimal separator. 

      The bug is easy to reproduce  sample code : 

      import Foundation
      
      // Required to call setLocale
      import Darwin
      
      // Let's set to french
      setlocale(LC_ALL,"fr_FR")
       
      struct Shot:Codable{
          let seconds:Double
      }
       
      let shot = Shot(seconds: 1.1)
       
      do{
          let data = try JSONEncoder().encode(shot)
          if let json =  String(data:data, encoding:.utf8){
              // the result is : "{"seconds":1,1000000000000001}"
              // should be : "{"seconds":1.1000000000000001}"
              // The decimal separator should not be "," but "."
              print(json)
          }
      }catch{
          print("\(error)")
      }
       
      exit(EX_OK)
       
      

       

      Here is my proposed fix  in `JSONSerialization.swift` line 308 . Specifying `kCFNumberFormatterDecimalSeparator` is required. `

       

          private lazy var _numberformatter: CFNumberFormatter = {
              let formatter: CFNumberFormatter
              formatter = CFNumberFormatterCreate(nil, CFLocaleCopyCurrent(), kCFNumberFormatterNoStyle)
              CFNumberFormatterSetProperty(formatter, kCFNumberFormatterMaxFractionDigits, NSNumber(value: 15))
             CFNumberFormatterSetProperty(formatter, kCFNumberFormatterDecimalSeparator,"."._cfObject)
              CFNumberFormatterSetFormat(formatter, "0.###############"._cfObject)
              return formatter
          }()
      

       

      Gonna try to submit this fix.

       

       

       

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                b Benoit Pereira da Silva
              • Votes:
                1 Vote for this issue
                Watchers:
                6 Start watching this issue

                Dates

                • Created:
                  Updated: