实现数字截取显示,转化为w格式

2021-08-14  本文已影响0人  毛小兔的头发还在吗

新建一个util.dart文件,在文件中写入如下转化方法(可根据具体显示需求调整内容)

///超过四位数的数字转化为w格式,如:38128 => 3.8w,381285 => 38.1w
formatCharCount(int count) {
  if (count <= 0 || count.isNaN) {
    return '0';
  }
  String strCount = count.toString();
  if(strCount.length >= 5) {
    String prefix = strCount.substring(0,strCount.length-4);
    if(strCount.length == 5) {
      prefix += '.${strCount[1]}';
    }
    if(strCount.length == 6) {
      prefix += '.${strCount[2]}';
    }
    return prefix + 'w';
  }
  return strCount;
}

创建好转化方法后,在需要转化的数字外包裹一层formatCharCount即可

示例:

import 'package:flutter/material.dart';
import 'package:demo/utils/util.dart';

class FormatCharCountPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title:Text('Format Char Count Page')
      ),
      body:Column(
        children: <Widget> [
          formatCharCount(1234),  //转化后显示为1234
          formatCharCount(12345),  //转化后显示为1.2w
          formatCharCount(123456),  //转化后显示为12.3w
          formatCharCount(1234567),  //转化后显示为123w
        ],
      ),
    );
  }
}
上一篇下一篇

猜你喜欢

热点阅读