Created
May 9, 2017 15:00
-
-
Save ronlobo/7000b5b1d070ed3e35deba5303792634 to your computer and use it in GitHub Desktop.
String format for Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static String format(String fmt,List<Object> params) { | |
int matchIndex = 0; | |
String replace(Match m) { | |
if (matchIndex<params.length) { | |
switch (m[4]) { | |
case "f": | |
num val = params[matchIndex++]; | |
String str; | |
if (m[3]!=null && m[3].startsWith(".")) { | |
str = val.toStringAsFixed(int.parse(m[3].substring(1))); | |
} else { | |
str = val.toString(); | |
} | |
if (m[2]!=null && m[2].startsWith("0")) { | |
if (val<0) { | |
str = "-"+str.substring(1).padLeft(int.parse(m[2]),"0"); | |
} else { | |
str = str.padLeft(int.parse(m[2]),"0"); | |
} | |
} | |
return str; | |
case "d": | |
case "x": | |
case "X": | |
int val = params[matchIndex++]; | |
String str = (m[4]=="d")?val.toString():val.toRadixString(16); | |
if (m[2]!=null && m[2].startsWith("0")) { | |
if (val<0) { | |
str = "-"+str.substring(1).padLeft(int.parse(m[2]),"0"); | |
} else { | |
str = str.padLeft(int.parse(m[2]),"0"); | |
} | |
} | |
return (m[4]=="X")?str.toUpperCase():str.toLowerCase(); | |
case "s": | |
return params[matchIndex++].toString(); | |
} | |
} else { | |
throw new Exception("Missing parameter for string format"); | |
} | |
throw new Exception("Invalid format string: "+m[0].toString()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
format("%d", [1]) // 1 | |
format("%02d", [2]) // 02 | |
format("%.2f", [3.5]) // 3.50 | |
format("%08.2f", [4]) // 00004.00 | |
format("%s %s", ["A","B"]) // A B | |
format("%x", [63]) // 3f | |
format("%04x", [63]) // 003f | |
format("%X", [63]) //3F |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment