I want to convert a low value double like (0.0003009585) to show as a currency ($0.0003).
Intl package NumberFormat() will show it as $0 for different currency formats.
Tried different RegexExp did’nt work.
These code also doesnot work
String numToCurrency(double num) {
final String numThreeZero = num.toStringAsFixed(2);
final String numWithComma = NumberFormat.decimalPattern().format(double.parse(numThreeZero));
if (numWithComma == '0') {
final strNum = num.toString();
String fixedNum = '';
for (int i = 0; i < strNum.length; i++) {
if (strNum[i] == '0' || strNum[i] == '.') continue;
fixedNum = num.toStringAsFixed(i);
}
return fixedNum;
} else {
return numWithComma;
}
}
3
Answers
Two logical mistakes I found and here is how to solve them.
Firstly,
num.toStringAsFixed(2)
will round the value to two decimal places and return a string representation of the number. However, this does not add any commas to the number.Secondly,
NumberFormat.decimalPattern()
will format the number with commas based on the user’s locale. It does not add a currency symbol or format the number as a currency.To format the number as a currency with two decimal places, you can use the
NumberFormat.currency()
method. Here is an example of how you can modify your code to achieve this:This will format the number as a currency with four decimal places (if available), with the currency symbol as $.
If you want to show only two decimal places and remove trailing zeros, you can modify the code as follows:
This will remove any trailing zeros after the decimal point and also remove any trailing
.00
.I hope you don’t mind some maths 🙂
You can use log to find the first non-zero digit.
Output:
0.0003
I guess this would be a simple solution