I would like to emulate C's sprintf("%02d", x);
in Dart, but I can't find string formatting, only string interpolation.
7 Answers
String interpolation covers most of your needs. If you want to format numbers directly, there is also num.toStringAsPrecision()
.
-
1That's helpful, but I need a way to combine precision and radix, e.g.
sprintf("%02x", 0x0f)
.– mcandreFeb 17, 2012 at 15:32 -
2not sure I agree the string interpolation covers everything. printf/format makes constructs such as sprintf("%08d", number) (format number with up to 8 leading zeroes) and sprintf("%.3f", number) (Round number to 3 digits after decimal point) very easy. Most languages I have used that has string interpolation also have a printf functionality (Perl, Ruby,...). Feb 17, 2012 at 16:25
I took a different approach to this issue: by padding the string directly, I don't have to use any libraries (mainly because the intl library seems to be discontinued):
x.toString().padLeft(2, "0");
Would be the equivalent of sprintf("%02d", x);
The intl library provides several helpers to format values. See the API documentation at http://api.dartlang.org/docs/releases/latest/intl.html
Here is an example on how to convert 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)));
}
A String.format method does not currently exists but there is a bug/feature request for adding it.
-
1
-
2@GünterZöchbauer, it looks like it does exist, but manages to trigger a 500 response. Searching the issue tracker for 'sprintf' will list it as an issue. From the listing page, the issue can be stared, if you want to follow it. Oct 31, 2014 at 4:51
Here is my implementation of String.format for Dart. It is not perfect but works good 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 modeled after C's sprintf.
See a format package. It is similar to format() from Python. It is a new package. Needs testing.