I am using userdefaults to save a decimal value of unknown length ( I.e. 51000000000) . Userdefaults does not allow for the saving of long decimal numbers, so I resorted to turning the value into a string and saving it. Then I want to re load the number however I have been unable to find a way to convert string value into a decimal. How do I do this?
Edit:
Code for setting the value into userdefaults:
let savedValues = UserDefaults.standard
savedValues.setValue(String(describing: buildingConstants.jitterClickConstantCost), forKey:"jitterClickCost")
struct buildingConstants {
static var jitterClickConstantCost = Decimal()
}
If the String contains a valid floating point value, then Swift will assign it to the floatValue constant which will be available within the if let scope. The result of this example will be printed as “Float value = 12.2416”.
The "%f" format string means "a floating point number," but "%. 2f" means "a floating-point number with two digits after the decimal point. When you use this initializer, Swift will automatically round the final digit as needed based on the following number.
In Swift, there are two types of floating-point number, both of which are signed. These are the Float type which represents 32-bit floating point numbers with at least 6 decimal digits of precision and the Double type which represents 64-bit floating point numbers at least 15 decimal digits of precision.
To convert a string to a double, we can use the built-in Double() initializer syntax in Swift. The Double() initializer takes the string as an input and returns the double instance.
You can try the default initializer for Decimal with a string parameter
here is an example
let decimal: Decimal = 51000000000
let str = String(describing: decimal)
let savedValues = UserDefaults.standard
savedValues.set(str, forKey:"jitterClickCost")
savedValues.synchronize()
let value = savedValues.string(forKey: "jitterClickCost") ?? "0"
let result = Decimal(string: value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With