Dart 有 sprintf 还是只有插值?
我想在 Dart 中模拟 C 的 sprintf("%02d", x);
,但我找不到字符串格式,只能找到字符串插值。
I would like to emulate C's sprintf("%02d", x);
in Dart, but I can't find string formatting, only string interpolation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
请参阅格式包。它类似于 Python 中的 format()。这是一个新包。需要测试。
See a format package. It is similar to format() from Python. It is a new package. Needs testing.
字符串插值可以满足您的大部分需求。如果想直接格式化数字,还有
num.toStringAsPrecision()
。
String interpolation covers most of your needs. If you want to format numbers directly, there is also
num.toStringAsPrecision()
.我对这个问题采取了不同的方法:通过直接填充字符串,我不必使用任何库(主要是因为 intl 库似乎已停止使用):
相当于 sprintf("%02d", x) ;
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):
Would be the equivalent of sprintf("%02d", x);
intl 库提供了几个格式化值的帮助器。
请参阅 API 文档 http://api.dartlang.org/docs/releases/ latest/intl.html
下面是如何将数字转换为两个字符串的示例:
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:
目前不存在 String.format 方法,但有一个 添加它的错误/功能请求。
A String.format method does not currently exists but there is a bug/feature request for adding it.
这是我为 Dart 实现的 String.format。它并不完美,但对我来说已经足够好了:
测试输出如下:
Here is my implementation of String.format for Dart. It is not perfect but works good enough for me:
Test output follows:
是的,Dart 有一个 sprintf 包:
https://pub.dev/packages/sprintf。
它是仿照C 的sprintf 设计的。
Yes, Dart has a sprintf package:
https://pub.dev/packages/sprintf.
It is modeled after C's sprintf.