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

在Blazor中为Chart.js 4的图表添加货币符号

Blazor + Chart.js 4.1:给Y轴和工具提示添加货币符号的解决办法

你的配置有几处不符合Chart.js 4.x的新API规范,直接修改以下几点就能解决问题:

1. 给Y轴刻度添加货币格式化

在Y轴的ticks配置里新增回调函数,将数字转换为带英镑符号+千分位的格式:

ticks = new
{
    color = "white",
    // 把刻度值格式化为£X,XXX样式
    callback = "function(value) { return '£' + value.toLocaleString(); }"
}

2. 替换过时的轴标题配置

Chart.js 4.x已废弃scaleLabel,改用title配置设置轴标题:

// 替换原来的scaleLabel节点
title = new
{
    display = true,
    text = "Sales Total £",
    color = "white"
}

3. 修正工具提示的配置位置与回调函数

Chart.js 4.x将工具提示移至plugins.tooltip节点下,同时回调参数结构也有变化,修改如下:

// 在Options中新增Plugins节点
Plugins = new
{
    Tooltip = new
    {
        Callbacks = new
        {
            // 格式化工具提示中的数值
            Label = "function(context) { return '£' + context.parsed.y.toLocaleString(); }"
        }
    }
}

完整修改后的配置代码

var config = new
{
    Type = Type.ToString().ToLower(),
    Options = new
    {
        Responsive = true,
        Scales = new
        {
            y = new
            {
                ticks = new
                {
                    color = "white",
                    callback = "function(value) { return '£' + value.toLocaleString(); }"
                },
                grid = new
                {
                    color = "white",
                    borderColor = "white",
                    drawOnChartArea = false
                },
                title = new
                {
                    display = true,
                    text = "Sales Total £",
                    color = "white"
                }
            },
            x = new
            {
                ticks = new
                {
                    color = "white"
                },
                grid = new
                {
                    color = "white",
                    borderColor = "white",
                    drawOnChartArea = false
                }
            }
        },
        Plugins = new
        {
            Tooltip = new
            {
                Callbacks = new
                {
                    Label = "function(context) { return '£' + context.parsed.y.toLocaleString(); }"
                }
            }
        }
    },
    Data = ChartData
};

如果需要美元符号,直接把代码中的£替换为$即可,toLocaleString()会自动添加千分位分隔符,提升数字可读性。

内容的提问来源于stack exchange,提问作者Musaffar Patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:01:13