PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How to get an absolute value from NSDecimalNumber?

 August 10, 2022     absolute-value, decimal, swift     No comments   

Issue

How to get an absolute value from NSDecimalNumber? Getting absolute value from Integer is easy, but I need one from NSDecimalNumber. I have found answers from few years ago (Objective-C, for example), but I was hoping that in Swift in 2020 it is easier now.

Code from my playground:

import UIKit

var str = "Hello, playground"

// absolute value

let intValue: Int = -5
let absoluteIntValue = abs(intValue) // works
print("\(absoluteIntValue)") // 5

let value: NSDecimalNumber = -5.234
let absoluteValue = abs(value) // doesn't work. Gives an error: Cannot convert value of type 'NSDecimalNumber' to expected argument type 'Int32'
print("\(absoluteValue)")

Solution

Just replace NSDecimalNumber with (native) Decimal. The generic abs function considers also the Decimal type

let value: Decimal = -5.234
let absoluteValue = abs(value) 
print(absoluteValue)


Answered By - vadian
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing