I want to have the integer value of the following floating point value:
var floatingPointValue = NSDate().timeIntervalSince1970 * 1000
I don't care if the integer value of this floating point number is actually an integer or a string.
Yes, an integral value can be added to a float value. The basic math operations ( + , - , * , / ), when given an operand of type float and int , the int is converted to float first. So 15.0f + 2 will convert 2 to float (i.e. to 2.0f ) and the result is 17.0f .
swift1min read To convert a float value to an Int, we can use the Int() constructor by passing a float value to it. Note: When we use this conversion the Integer is always rounded to the nearest downward value, like 12.752 to 12 or 6.99 to 6 .
Unless you need to work with a specific size of integer, always use Int for integer values in your code. This aids code consistency and interoperability. Even on 32-bit platforms, Int can store any value between -2,147,483,648 and 2,147,483,647 , and is large enough for many integer ranges.
Since a float is bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that typecasting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value.
Int64
is large enough to hold a time interval of some million
years measured in milliseconds:
let milliSeconds = Int64(someDate.timeIntervalSince1970 * 1000)
let milliSecondsString = String(milliSeconds)
Int64 is enough to hold the value you needed
let floatingPointValue = NSDate().timeIntervalSince1970 * 1000
let intValue = Int64(floatingPointValue)
The crucial part is to use Int64
instead of Int
on 32-bit platforms. It will allow you to use 8 bytes of memory (from −9223372036854775808 to +9223372036854775807)
Int64(NSDate().timeIntervalSince1970 * 1000)
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