简体   繁体   English

C#中的小数舍入

[英]Decimal Rounding in C#

I have code that is taking information from the database to insert into a list. 我有从数据库中获取信息以插入列表的代码。 One piece of data that I'm taking will be used for price. 我要获取的一项数据将用作价格。 (I set its type to decimal in SQL Server), for example: " 1,80". (我在SQL Server中将其类型设置为十进制),例如:“ 1,80”。

But when I select it, my decimal variable returns the value 2 ! 但是,当我选择它时,我的十进制变量返回值2!

I want to know if there are a simple way to make decimal not automatically round numbers. 我想知道是否有一种简单的方法来使小数点不自动舍入数字。

This is the code: 这是代码:

public decimal preco { get; set; } 

while (dr.Read())
{
    clsCaProd oProd = new clsCaProd();
    oProd.cod = dr.GetInt32(0);
    oProd.preco = dr.GetDecimal(1); // Here returns "2" instead of "1,80"
    oProd.info = dr.GetString(2);
    oProd.categ = dr.GetString(3);
    oProd.nome = dr.GetString(4);

    lProd.Add(oProd);
}

If you declare a column as decimal , the default "scale" is zero. 如果将一列声明为decimal ,则默认的“ decimal ”为零。 You need to specify the precision and scale . 您需要指定精度和小数位数

Try this example : 试试这个例子

declare @d1 decimal = 1.80
declare @d2 decimal(19,4) = 1.80

select @d1, @d2;

Results: 结果:

2        1.8000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM