You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何修改数字小数点后部分的字体大小

效果示例

实现方法

核心实现逻辑是将数字字符串按小数点拆分为整数、小数两个部分,通过RichText组件的TextSpan分别为两部分配置不同的字号、字重、颜色样式即可,这种方式天然支持文本基线对齐,不会出现多个Text组件拼接时的错位问题。

可复用封装组件

直接封装通用组件,支持自定义整数/小数样式、保留小数位数:

import 'package:flutter/material.dart';

class DifferentSizeDecimalText extends StatelessWidget {
  final num value;
  /// 整数部分(含负号、千分位符号)文本样式
  final TextStyle integerTextStyle;
  /// 小数点+小数部分文本样式
  final TextStyle decimalTextStyle;
  /// 保留小数位数
  final int decimalDigits;

  const DifferentSizeDecimalText({
    super.key,
    required this.value,
    required this.integerTextStyle,
    required this.decimalTextStyle,
    this.decimalDigits = 2,
  });

  @override
  Widget build(BuildContext context) {
    // 统一格式化数字,固定小数位数
    final formattedNum = value.toStringAsFixed(decimalDigits);
    final splitParts = formattedNum.split('.');

    return RichText(
      text: TextSpan(
        children: [
          TextSpan(text: splitParts[0], style: integerTextStyle),
          if (splitParts.length > 1)
            TextSpan(text: '.${splitParts[1]}', style: decimalTextStyle),
        ],
      ),
    );
  }
}

调用示例

DifferentSizeDecimalText(
  value: 1258.56,
  integerTextStyle: const TextStyle(
    fontSize: 34,
    fontWeight: FontWeight.w700,
    color: Color(0xFF1A1A1A),
  ),
  decimalTextStyle: const TextStyle(
    fontSize: 18, // 小数部分设置更小字号
    fontWeight: FontWeight.w500,
    color: Color(0xFF666666),
  ),
  decimalDigits: 2,
)

扩展说明

  • 如果需要给小数点单独设置样式,只需要把拼接逻辑里的.拆成独立的TextSpan单独配置样式即可
  • 如果需要千分位展示,可先对整数部分字符串做千分位格式化处理,再传入TextSpan,不影响样式拆分逻辑
  • 不要使用Row嵌套多个Text组件做拼接,不同字号的文本会出现基线不对齐、上下错位的问题,RichText会自动处理不同字号Span的基线对齐,显示效果更自然

内容的提问来源于stack exchange,提问作者Aanand S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 06:39:16