Skip to content

Decimal values Precision #3535

Closed
Closed
@satyaaiosdev

Description

@satyaaiosdev

Summary

We have sending GraphQL.Decimal(decimal: 6.99) but backend sending 6.990000000000002, why add more precision of Decimal number need to rounded two decimals, can you help me out this.

CustomScalors > Decimals automatically genarated SPM side as below

import ApolloAPI
import struct Foundation.Locale
import struct Foundation.Decimal
import struct Foundation.NSInteger
import class Foundation.NSNumber
import class Foundation.NumberFormatter

/// Fixed precision (up to 2 decimal places) numeric value.
public struct Decimal: CustomScalarType, Hashable {
public let decimal: Foundation.Decimal

public init(decimal: Foundation.Decimal) {
self.decimal = decimal
}

public init(intValue: Foundation.NSInteger) {
self.decimal = Foundation.Decimal(intValue)
}

public init (_jsonValue value: JSONValue) throws {
if
let valueString = value as? String,
let parseResult = Foundation.Decimal(string: valueString),
!parseResult.isNaN
{
self.decimal = parseResult
} else if
let valueDouble = value as? Double,
let parseResult = valueDouble.truncatedDecimal,
!parseResult.isNaN
{
self.decimal = parseResult
} else {
throw JSONDecodingError.couldNotConvert(value: value, to: Decimal.self)
}
}

public var _jsonValue: JSONValue {
decimal
}
}

private let truncationFormatter = {
let formatter = Foundation.NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.roundingMode = .up
formatter.locale = Locale(identifier: "en_US")
return formatter
} ()

public extension Double {
var truncatedDecimal: Foundation.Decimal? {
guard !self.isNaN else {
return nil
}

return truncationFormatter.string(from: self as NSNumber).flatMap { Foundation.Decimal(string: $0) }

}
}

Version

1.0.7

Steps to reproduce the behavior

every decimal value

Logs

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions