A simple extension for currency format on string in Dart
Hello this in my first article in english language and very sorry for my bad english writing.
in this article i want to share my experience in add currency format to string without package
void main() {
print("1000".currency());
print("1300000".currency());
print("1005000".currency(symbol: '£'));
print("1000000".currency(symbol: '€'));
}extension StringFormatter on String{
String currency({String symbol = "\$"}) {
int step = 1;
String val = this;
for (var i = val.length-1; i >=0; i--) { if (i - 2*step > 0) {
val = val.replaceRange(i-2*step, i-2*step, ",");
step++;
}
}
return "$symbol$val";
}
}
extension in dart is a feature that help you to add functions to other class that you don’t write it. and in here i am write extension for String class
Okay lets go to explain the code:
we have for loop from end to start of our string because splitter for currency start from write of price
we need to add character every 3 char for example: “,”
I used replaceRange method to insert character in special index.
How to find correct index to insert character? I am consider a variable for step that initial with 1. okay we need to check if we back 3 char before is grater than 0 and if true we can insert symbol each 3 char.
if we wanna for example 4 char it just need to replace 2 with 3 and
Done!