Skip to content# Removing Decimals from a Number in Swift

## Using the Int() Constructor

## Using the floor() Function

## Using the truncatingRemainder(dividingBy:) Method

## Summary

— Swift, iOS Development — 1 min read

When working with numbers in Swift, sometimes you may need to remove the decimal part of a floating-point number to get an integer value. There are several ways to achieve this in Swift. In this post, we will discuss some of the most commonly used techniques to remove decimals from a number in Swift.

One way to remove decimals from a number in Swift is by using the `Int()`

constructor. This constructor creates an integer value from a floating-point number by truncating the decimal part. Here is an example:

`1let number = 12.342let integer = Int(number)3print(integer) // Output: 12`

In the above example, we create a floating-point number `12.34`

and convert it to an integer using the `Int()`

constructor. The output of the above code is `12`

, which is the integer value obtained after removing the decimal part.

Another way to remove decimals from a number in Swift is by using the `floor()`

function. This function returns the largest integer value less than or equal to the given number. Here is an example:

`1let number = 12.562let integer = Int(floor(number))3print(integer) // Output: 12`

In the above example, we create a floating-point number `12.56`

and apply the `floor()`

function to it. The output of the above code is `12`

, which is the integer value obtained after removing the decimal part.

You can also remove decimals from a number in Swift by using the `truncatingRemainder(dividingBy:)`

method. This method returns the remainder of the division operation performed on the given number. Here is an example:

`1let number = 12.782let integer = Int(number.truncatingRemainder(dividingBy: 1))3print(integer) // Output: 12`

In the above example, we create a floating-point number `12.78`

and apply the `truncatingRemainder(dividingBy:)`

method to it with a divisor of 1. The output of the above code is `12`

, which is the integer value obtained after removing the decimal part.

In this post, we have discussed different ways to remove decimals from a number in Swift. You can use the `Int()`

constructor, the `floor()`

function, or the `truncatingRemainder(dividingBy:)`

method to obtain the integer value without the decimal part.

- The
`Int()`

constructor creates an integer value from a floating-point number by truncating the decimal part. - The
`floor()`

function returns the largest integer value less than or equal to the given number. - The
`truncatingRemainder(dividingBy:)`

method returns the remainder of the division operation performed on the given number.