Application scenarios

The UI page needs to display data with n decimal places reserved, but currently the data is not a String. At this point, you need to convert this data to String.

API and language

String

Swift

Core logic/code

Double is converted to String

Use the “\(any base-type data)” method in the String API to convert the type to String.

If you want to convert a String from Double to a decimal. You can initialize the method with String(format:) of String. The decimal places reserved in this method are rounded.

String is converted to Double

Cast directly using Double(the converted String). Note in particular that String must be converted data, otherwise the converted data will be nil

Converting a String to an Int

If the String is converted to “2.78”, it returns nil when it is converted to Int

The sample code

Double is converted to String

Let double = double (2.7895) // double = double (2.7895) // double = double (2.7895) // print(2.7895) Double) // output "2.79"Copy the code

String is converted to Double

// double double = double (doubleStr) // if STR is not data, Let doubleStr = "doubleStr" let double = double (doubleStr) // nilCopy the code

Note that Int is converted to String

Let intStr = "2.78" let Int = Int(intStr) // nilCopy the code