gpt4 book ai didi

c# - 为什么 Convert.ToDecimal 返回不同的值

转载 作者:太空狗 更新时间:2023-10-29 21:45:15 24 4
gpt4 key购买 nike

我希望有人可以帮助我理解为什么在 linq 中使用 Convert.ToDecimal 时会四舍五入小数点,而在外部使用时却不会

给定以下数据库:

CREATE TABLE [dbo].[Widgets](
[ID] [int] NOT NULL,
[WidgetName] [varchar](50) NOT NULL,
[UnitsAvailable] [int] NOT NULL,
[WeightInGrams] [decimal](10, 6) NULL
) ON [PRIMARY]
GO

INSERT [dbo].[Widgets] VALUES (1, N'Best thing ever', 100, CAST(10.000210 AS Decimal(10, 6)))
INSERT [dbo].[Widgets] VALUES (2, N'Next Best thing', 50, CAST(100.000151 AS Decimal(10, 6)))
INSERT [dbo].[Widgets] VALUES (3, N'The Other Model', 25, CAST(5.231651 AS Decimal(10, 6)))

代码:

class Program
{
static void Main(string[] args)
{

Console.WriteLine("------Example 1--------");

LqToSqlDataContext _ctx = new LqToSqlDataContext();

List<Widget> inventory = (from c in _ctx.linqWidgets
select new Widget()
{
Id = c.ID,
Name = c.WidgetName,
UnitsOnHand = c.UnitsAvailable,
WeightInGrams = Convert.ToDecimal(c.WeightInGrams)
}).ToList();

foreach(Widget w in inventory)
{
Console.WriteLine(w.ToString());
}


Console.WriteLine("------Example 2--------");

var _linqInventory = _ctx.linqWidgets;
Widget temp = null;

foreach(linqWidget lw in _linqInventory)
{
temp = new Widget();
temp.Id = lw.ID;
temp.Name = lw.WidgetName;
temp.UnitsOnHand = lw.UnitsAvailable;
temp.WeightInGrams = Convert.ToDecimal(lw.WeightInGrams);

Console.WriteLine(temp.ToString());
}



Console.ReadLine();
}
}

class Widget
{
public int Id { get; set; }
public string Name { get; set; }
public int UnitsOnHand { get; set; }
public decimal WeightInGrams { get; set; }

public override string ToString()
{
return this.Id + "\t" + this.Name + "\t" + this.UnitsOnHand + "\t" + this.WeightInGrams;
}
}

输出

------Example 1--------
1 Best thing ever 100 10.0002
2 Next Best thing 50 100.0002
3 The Other Model 25 5.2317
------Example 2--------
1 Best thing ever 100 10.000210
2 Next Best thing 50 100.000151
3 The Other Model 25 5.231651

最佳答案

因为 LinqtoSql 将 Convert.ToDecimal 翻译成一条 sql 语句,如 CONVERT(DECIMAL({someNumberLinqComesupWith}, 4)

关于c# - 为什么 Convert.ToDecimal 返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16965856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com