Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Split a double by dot to two numbers

So I am trying to split a number in swift, I have tried searching for this on the internet but have had no success. So first I will start with a number like:

var number = 34.55

And from this number, I want to create two separate number by splitting from the dot. So the output should be something like:

var firstHalf = 34
var secondHalf = 55

Or the output can also be in an array of thats easier. How can I achieve this?

like image 824
Sachin Avatar asked Feb 14 '15 03:02


People also ask

How do you truncate a double to two decimal places?

DecimalFormat("#. ##") - Here, I entered two hash symbols(##) after the decimal point. Hence, this will truncate the number up to two decimal places. This will work for both Positive & Negative values.

How do you split a float number?

Using the modulo ( % ) operator If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.

How do you round double to 2 decimals in Swift?

By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

1 Answers

The easiest way would be to first cast the double to a string:

var d = 34.55
var b = "\(d)" // or String(d)

then split the string with the global split function:

var c = split(b) { $0 == "." }   // [34, 55]

You can also bake this functionality into a double:

extension Double {
    func splitAtDecimal() -> [Int] {
        return (split("\(self)") { $0 == "." }).map({
            return String($0).toInt()!

This would allow you to do the following:

var number = 34.55
print(number.splitAtDecimal())   // [34, 55]
like image 174
royhowie Avatar answered Sep 22 '22 12:09