A Swift PRINTUSING (ie. Xojo-Like 'Format') Function (topic renamed)

Does anyone have a method that replicates what the Xojo Format Function does? I don’t want a built-in function, but rather a “long hand” version. What I want to do, if add this feature to my SWIFT String library. It does support the “C” Printf type formats ("%02D" etc), but I want something that works as close to how Xojo does it as possible.

Turns out Swift DOES have such a function after all… (NumberFormatter)

1 Like

Here is my implemetation of Printusing for SWIFT

import Foundation
func printusing(_ number:Int, _ pattern:String)    -> String { return printusing(Double(number),pattern) }
func printusing(_ number:Double,_ pattern:String) -> String {
	//
	// pattern cal be 3 segments <postive>;<negative>;<zero> // zero returns the literal pattern
	//
	// [#]   Placeholder that displays the digit from the value if it is present.
	//
	// [0]   Placeholder that displays the digit from the value if it is present, a Zero otherwise
	//
	// [+]	 Displays the plus sign to the left of the number if the number is positive or a minus sign if the number is negative.
	//
	// [-]	 Displays a minus sign to the left of the number if the number is negative. There is no effect for positive numbers.
	//
	// [%]	 Displays the number multiplied by 100.
	//
	// [E+0] Displays the number in scientific notation. [the +0 is required]
	//
	// [**]  A double asterisk will pad output
	//
	var p        : [String] = Split(pattern,";")
	var _pattern : String   = ""
	if p.count==1 { p.append(p[0]) }
	if p.count==2 { p.append(p[0]) }
	if number>0 {
		_pattern = p[0]
	} else if number<0 {
		_pattern = p[1]
	} else { _pattern=p[2] } // zero returns literal pattern
	if InStr(_pattern,"#")+InStr(_pattern,"0") == 0 { return _pattern }
	let numberFormatter            = NumberFormatter()
	numberFormatter.positiveFormat = _pattern
	let output : String            = numberFormatter.string(from: NSNumber(value: number))!
	return output
	//
	// NOTE : requires DSString Library
	//
}

Example :

let p = "S#.0E+0;######.###;Zero"
print(printusing(+238384579823457239440.38,p))
print(printusing(-238384579823457239440.38,p))
print(printusing(0,p))

Output

S2E+20
-238384579823457240000
Zero