Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a floating point value greater than Int.max to Int in Swift

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.

like image 609
DrCachetes Avatar asked Feb 11 '15 13:02

DrCachetes


People also ask

Can you add float to int?

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 .

How do I cast an int in Swift?

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 .

How large can an int be in Swift?

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.

How do you find the int value of a float?

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.


Video Answer


3 Answers

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)
like image 154
Martin R Avatar answered Oct 22 '22 22:10

Martin R


Int64 is enough to hold the value you needed

let floatingPointValue = NSDate().timeIntervalSince1970 * 1000
let intValue = Int64(floatingPointValue)
like image 41
jaiswal Rajan Avatar answered Oct 22 '22 22:10

jaiswal Rajan


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)
like image 31
yoAlex5 Avatar answered Oct 22 '22 20:10

yoAlex5