0

I have function:

func toString(number: Decimal, scale: Int) -> String {
    return number
}

I need a function that in the "number" parameter - will receive a Decimal number, round it to the number of decimal places (scale parameter) and return the result in the String. Does anyone know how to do it?

Sunil Targe
  • 7,251
  • 5
  • 49
  • 80
traff
  • 135
  • 5

3 Answers3

0
func toString(number: Double, scale: Int)-> String 
{

    var tempNum = number*pow(10.0,Double(scale))
    tempNum.round(.towardZero)

    return "\(tempNum*pow(10,(-1)*Double(scale)))"
}
Sunil Targe
  • 7,251
  • 5
  • 49
  • 80
marc
  • 914
  • 6
  • 18
  • I have error in line: Binary operator '*' cannot be applied to operands of type 'Decimal' and 'Double' – traff Jul 20 '18 at 07:21
  • Please make sure you copied the first line of the function in which I wrote "toString(number : Double..." – marc Jul 20 '18 at 07:25
0
extension decimal
    {
        func roundTo(places:Int) -> String
        {
            let divisor = pow(10.0, Double(places))
            return "\((self * divisor).rounded() / divisor)"
        }
    }

I think this extension could help you. I use this is nearly every project.

Fabian Gr
  • 215
  • 1
  • 12
  • I have error in line: number.roundTo(places: scale) - Value of type 'Decimal' has no member 'roundTo' – traff Jul 20 '18 at 07:23
  • edited my answer should work for decimal if you use it now. it has been a Double extension not an decimal extension. – Fabian Gr Jul 20 '18 at 07:27
0
let numberFormatter = NumberFormatter()
numberFormatter.minimumIntegerDigits = 1
numberFormatter.minimumFractionDigits = 0

func toString(number: NSNumber, scale: Int) -> String {
    numberFormatter.maximumFractionDigits = scale
    return numberFormatter.string(from: number) ?? ""
}

EXAMPLES:

toString(number: NSNumber(value: 1234.5678), scale: 1) // ANSWER = 1234.6
toString(number: NSNumber(value: 1234.5678), scale: 2) // ANSWER = 1234.57
toString(number: NSNumber(value: 1234.5678), scale: 3) // ANSWER = 1234.568
toString(number: NSNumber(value: 1234.5678), scale: 4) // ANSWER = 1234.5678
toString(number: NSNumber(value: 1234.5678), scale: 5) // ANSWER = 1234.5678
  • I'm try your code: public func toString( number: Decimal, scale: Int)-> String { return toString2(number: NSNumber(value: number), scale: scale) } func toString2(number: NSNumber, scale: Int) -> String { let numberFormatter = NumberFormatter() numberFormatter.minimumIntegerDigits = 1 numberFormatter.minimumFractionDigits = 0 numberFormatter.maximumFractionDigits = scale return numberFormatter.string(from: number) ?? "" } - and I have error: Argument labels '(value:)' do not match any available overloads – traff Jul 20 '18 at 07:28