Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to decimal swift

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()
}
like image 740
R. Duggan Avatar asked Mar 14 '17 18:03

R. Duggan


People also ask

How do I convert a string to a Float in Swift?

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”.

How do I show only 2 digits after a decimal in Swift?

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.

What is decimal type in Swift?

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.

How do I convert a string to a double in Swift?

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.


1 Answers

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)
like image 50
zombie Avatar answered Oct 03 '22 01:10

zombie