Created
May 7, 2020 08:02
-
-
Save roipeker/1d7b26d0a5ab97723802b90ec29aa96a to your computer and use it in GitHub Desktop.
Quick currency formatter implementation test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:math'; | |
import 'package:intl/intl.dart'; | |
void main(List<String> arguments) { | |
// Intl.defaultLocale = 'es_AR'; | |
Intl.defaultLocale = 'en_US'; | |
// Should be calculated only on locale change to modify the separators. | |
// -- start static implementation. | |
var base = NumberFormat.currency(decimalDigits: 1, symbol: ''); | |
var formato = base.format(1000.1); | |
var decimalSep = formato[5]; | |
var thousandSep = formato[1]; | |
// -- end of static | |
// utility method | |
String formatCurrency( | |
{int decimals = 2, int amount, String prefix, String suffix}) { | |
prefix ??= ''; | |
suffix ??= ''; | |
var intValue = ''; | |
var units = amount / pow(10, decimals); | |
var units_arr = '$units'.split('.'); | |
var intList = units_arr.first.split(''); | |
var len = intList.length - 1; | |
for (var i = 0; i <= len; ++i) { | |
intValue += intList[i]; | |
if ((len - i) % 3 == 0 && i != len) intValue += thousandSep; | |
} | |
// integer part | |
var output = '$prefix$intValue'; | |
var decValue = units_arr[1]; | |
if (decValue != '0') { | |
if (decValue.length > decimals) { | |
decValue = decValue.substring(0, decimals); | |
} else { | |
decValue = decValue.padRight(decimals, '0'); | |
} | |
output += decimalSep + decValue; | |
} | |
output += '$suffix'; | |
print(output); | |
return output; | |
} | |
formatCurrency(decimals: 2, amount: 1001231231, prefix: '\$ ', suffix: ' s/IVA'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment