[ACCEPTED]-Does Dart have sprintf, or does it only have interpolation?-dart
String interpolation covers most of your 2 needs. If you want to format numbers directly, there 1 is also num.toStringAsPrecision()
.
A String.format method does not currently exists but 1 there is a bug/feature request for adding it.
The intl library provides several helpers 3 to format values. See the API documentation 2 at http://api.dartlang.org/docs/releases/latest/intl.html
Here is an example on how to convert 1 a number into a two character string:
import 'package:intl/intl.dart';
main() {
var twoDigits = new NumberFormat("00", "en_US");
print(twoDigits.format(new Duration(seconds: 8)));
}
I took a different approach to this issue: by 4 padding the string directly, I don't have 3 to use any libraries (mainly because the 2 intl library seems to be discontinued):
x.toString().padLeft(2, "0");
Would 1 be the equivalent of sprintf("%02d", x);
Here is my implementation of String.format 2 for Dart. It is not perfect but works good 1 enough for me:
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());
}
Test output follows:
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
Yes, Dart has a sprintf package: https://pub.dev/packages/sprintf. It is 1 modeled after C's sprintf.
See a format package. It is similar to format() from Python. It 1 is a new package. Needs testing.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.