Search code examples
flutterdartformatter

How to format money as millions in flutter?


I have formatted 500000 to 500k using Number formatter like this

NumberFormat.compact().format(int.parse(player.price!))

but i want to convert the number to half million like this 0.5m

is it possible ?


Solution

    • The official method provided by Flutter is difficult to do this, so I wrote this
          test('1515'); //0.002M
          test('1215'); //0.001M
          test('151555'); // 0.152M
          test('1511445'); // 0.151M
          test('15114455'); // 15.1M
    
      String test(String str) {
        var result = NumberFormat.compact(locale: 'en').format(int.parse(str));
        if (result.contains('K') && result.length > 3) {
          result = result.substring(0, result.length - 1);
          var prefix = (result.split('.').last.length) + 1;
          var temp = (double.parse(result) * .001).toStringAsFixed(prefix);
          result = double.parse(temp).toString() + 'M';
        }
        return result;
      }