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

.NET中小数表示异常:ASP.NET CRUD价格列输入值错误

问题分析与解决方法

这个问题核心是区域文化差异导致的数值解析错误:当你输入15.50时,应用程序的当前文化设置可能把小数点.识别成了千位分隔符,从而将输入解析为1550,后续的存储或格式化逻辑错误处理后,最终变成1.550。

以下是具体解决步骤:

1. 修正模型的格式化属性

你当前的DisplayFormat只控制显示,不影响输入解析。需要添加ApplyFormatInEditMode = true,同时改用更适合输入场景的数值格式(货币格式带符号可能干扰解析):

[Column("Valor")]
[Display(Name = "Valor")]
[DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
public decimal Valor { get; set; }

{0:N2}会确保编辑和显示时都保留两位小数,避免格式混淆。

2. 全局设置应用程序的区域文化

如果你的目标用户使用点作为小数点(比如中文、英文地区),可以统一配置应用的默认文化:

ASP.NET Core(Program.cs)

var cultureInfo = new CultureInfo("zh-CN"); // 或"en-US"
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

ASP.NET Framework(Global.asax)

protected void Application_BeginRequest(object sender, EventArgs e)
{
    CultureInfo culture = new CultureInfo("zh-CN");
    Thread.CurrentThread.CurrentCulture = culture;
    Thread.CurrentThread.CurrentUICulture = culture;
}

全局统一文化后,整个应用都会用指定规则解析数值,避免分隔符识别错误。

3. 检查数据库字段类型

确保数据库中Valor对应的字段类型是decimal(18,2)(或更高精度但保留两位小数),避免存储时的精度丢失或自动转换异常。

4. 前端输入验证(可选)

在页面输入框添加规则,限制输入格式:

<input asp-for="Valor" type="number" step="0.01" class="form-control" />

type="number"和step="0.01"会强制用户只能输入合法的小数,从源头减少格式错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 00:00:19