将文本框值转换为单个值会在C#中增加额外的精度

时间:2021-09-17 16:33:42

While converting value of a textbox to Convert.ToSingle() adds some extra precision for values like 2.7 to 2.7999999523162842. I don't want any rounding of this value because I have to store the exact value entered by the user to DB. So if any one have this issue before please post the solution, any help will appreciated.

将文本框的值转换为Convert.ToSingle()时,会为2.7到2.7999999523162842之类的值添加一些额外的精度。我不希望任何舍入此值,因为我必须将用户输入的确切值存储到DB。因此,如果任何人有此问题,请发布解决方案,任何帮助将不胜感激。

1 个解决方案

#1


3  

That's because a float is a binary fraction which cannot exactly represent the number 2.7 -- when you try to assign a number that is not a binary fraction to a float or a double, you will inevitably end up with an inexact representation.

这是因为浮点数是一个二进制小数,它不能精确地表示数字2.7 - 当你尝试将一个不是二进制小数的数字赋给float或double时,你将不可避免地得到一个不精确的表示。

You need use a decimal if you don't want to precise represent decimal numbers like 2.7.

如果您不想精确表示像2.7这样的十进制数,则需要使用小数。

var myDecimal = Convert.ToDecimal(input);

SImilarly, to store this value in a sql server database you need to use a SQL data type capable of storing precise decimal numerics. Conventiently, this data type is called decimal in SQL as well

实际上,要将此值存储在sql server数据库中,您需要使用能够存储精确十进制数字的SQL数据类型。顺便提一下,这种数据类型在SQL中也称为十进制

#1


3  

That's because a float is a binary fraction which cannot exactly represent the number 2.7 -- when you try to assign a number that is not a binary fraction to a float or a double, you will inevitably end up with an inexact representation.

这是因为浮点数是一个二进制小数,它不能精确地表示数字2.7 - 当你尝试将一个不是二进制小数的数字赋给float或double时,你将不可避免地得到一个不精确的表示。

You need use a decimal if you don't want to precise represent decimal numbers like 2.7.

如果您不想精确表示像2.7这样的十进制数,则需要使用小数。

var myDecimal = Convert.ToDecimal(input);

SImilarly, to store this value in a sql server database you need to use a SQL data type capable of storing precise decimal numerics. Conventiently, this data type is called decimal in SQL as well

实际上,要将此值存储在sql server数据库中,您需要使用能够存储精确十进制数字的SQL数据类型。顺便提一下,这种数据类型在SQL中也称为十进制