So at the moment, I have a number represented by counter. The number is incremental and continues to change. My goal is to add commas every 3 digits to make the number more readable in my app. The only issue that I am running into is that
String number = counter.replaceAllMapped(new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
(Match m) => '${m[1]},');
refuses to take the integer counter
as an int. How do I convert int counter
into String middle
before running it through
String number = middle.replaceAllMapped(new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
(Match m) => '${m[1]},');
My goal is this:
counter = 1000;
middle = "1000";
number = "1,000";
Will my current solution even work? If not, how do I change my code to meet my goal?
Update: Here is my code:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int counter = 0;
void _incrementCounter() {
setState(() {
if (counter > 99999999) {
//WinLandingPage();
} else if (counter >= 99000000) {
counter++;
} else if (counter > 990000) {
counter += 1000000;
} else if (counter > 9900) {
counter += 10000;
} else if (counter > 99) {
counter += 100;
} else counter++;
});
}
//BELOW is where the format is taking place, and I have no idea how to
//get this part working. This is my broken attempt.
var f = new NumberFormat("#,###,###,###", "en_US");
var number = f.format(counter);
//What am I doing wrong here?
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar (
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'Try to get $number to 100,000,000.',
),
new Text(
'$number',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
backgroundColor: Colors.pinkAccent,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
What am I doing wrong in this piece of code? I am super unfamiliar with Dart, but I am doing my best to figure it out from trial, error, and support from you guys.
答案 0 :(得分:4)
您可以使用NumberFormat包中的intl来执行此操作
README.md的一个例子
var f = new NumberFormat("###.0#", "en_US");
print(f.format(12.345));
==> 12.34
你的例子可能是
var f = new NumberFormat("#,###", "en_US");
print(f.format(1000));
==> 1,000