【问题标题】:How to format numbers as thousands separator in Flutter and Dart?如何在 Flutter 和 Dart 中将数字格式化为千位分隔符?
【发布时间】:2023-01-06 23:38:59
【问题描述】:

我需要格式数字作为千位分隔符,在字符串和数字上飞镖和飞镖。 为此,通常建议使用 intl package,但我更喜欢使用扩展而不使用 intl 包。

例如: 当我有这样的文本时:“+2500000.7550”,我的最终输出将交付为“+2,500,000.7550”和 当我有这样的文本时:“5674565544112211”,我的最终输出将作为“5674-5655-4411-2211”交付。

最后,我希望能够以特定模式(例如 2×2、3×3 或 4×4)通过特定字符分隔字符串变量。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    我试图通过编写这个扩展来解决这个挑战,但如果有更好的解决方案或代码,我将不胜感激。

    extension SubString on String {
      String addSeparator({int? qty = 3, String? separator = ","}) {
        assert(qty! >= 1, "[qty] value as the number separator must be positive!");
        assert(
            separator! != "", "[separator] value as the number separator must not be empty!");
        
         String tempNum=this;
         String sign="";
         String decimal="";
    
    
      if(RegExp(r'^[-+]?[0-9](d+.?d*|.d+)').hasMatch(this)){ 
        if(this[0]=="+"||this[0]=="-"){
        sign=this[0];
        tempNum=this.substring(1);
      }
        if(tempNum.contains(".")){
              decimal="."+tempNum.split(".")[1];
          tempNum=tempNum.split(".")[0];
        }
      }
        
        return sign+(tempNum.split('')
            .reversed
            .join()
            .replaceAllMapped(
                RegExp(r'(.{})(?!$)'.replaceAll('''{}''', '''{$qty}''')),
                (m) => '${m[0]}${separator}')
            .split('')
            .reversed
            .join())+decimal;
      }
    }
    

    并像下面的代码一样使用它:

    void main() {
      
      String numberExample = "+4654654.23535";
      
      print('numberExample:  ${numberExample.addSeparator(qty: 3,separator: ",")}');
    
      String ibanExample= "5674565544112211";
      
      print('ibanExample: ${ibanExample.addSeparator(qty: 4,separator: "-")}'); 
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多