Корректируя десятичную точность, .NET

Мы храним широту/долготу X 1,000,000 в нашей базе данных оракула, поскольку ЧИСЛА для предотвращения округляют ошибки с, удваивается.

, Учитывая, что широта/долгота к 6-му десятичному разряду была точностью на 10 см, которая была всем, которое нам было нужно. Много других баз данных также хранят lat/long к 6-му десятичному разряду.

63
задан Amy B 15 July 2009 в 17:24
поделиться

6 ответов

Preserving trailing zeroes like this was introduced in .NET 1.1 for more strict conformance with the ECMA CLI specification.

There is some info on this on MSDN, e.g. here.

You can adjust the precision as follows:

  • Math.Round (or Ceiling, Floor etc) to decrease precision (b from c)

  • Multiply by 1.000... (with the number of decimals you want) to increase precision - e.g. multiply by 1.0M to get b from a.

49
ответ дан 24 November 2019 в 16:27
поделиться
6
ответ дан 24 November 2019 в 16:27
поделиться

Вы просто видите разные представления одних и тех же данных. значение, состоящее из знака, a числовое значение, где каждая цифра в значение варьируется от 0 до 9, а a коэффициент масштабирования, который указывает положение десятичной запятой с плавающей запятой разделяющий интеграл и дробные части числового значения.

Двоичное представление Decimal значение состоит из 1-битного знака, 96-битное целое число и масштабирование коэффициент, используемый для деления 96-битного целое число и укажите, какая его часть является десятичной дробью. Масштабирование фактор - это неявно число 10, возведен в степень от 0 до 28. Следовательно, двоичная представление десятичного значения формы, ((-2 96 до 2 96 ) / 10 (от 0 до 28) ), где -2 96 -1 равно MinValue, а 2 96 -1 равно MaxValue.

Коэффициент масштабирования также сохраняет любые конечные нули в десятичном числе. Завершающие нули не влияют на значение десятичного числа в арифметические операции или операции сравнения. Однако конечные нули могут быть обнаруживается методом ToString, если применяется соответствующая строка формата.

18
ответ дан 24 November 2019 в 16:27
поделиться

The question is - do you really need the precision stored in the decimal, rather than just displaying the decimal to the required precision. Most applications know internally how precise they want to be and display to that level of precision. For example, even if a user enters an invoice for 100 in an accounts package, it still prints out as 100.00 using something like val.ToString("n2").

How can I create b from a? How can I create b from c?

c to b is possible.

Console.WriteLine(Math.Round(2.00000000m, 1)) 

produces 2.0

a to b is tricky as the concept of introducing precision is a little alien to mathematics.

I guess a horrible hack could be a round trip.

decimal b = Decimal.Parse(a.ToString("#.0"));
Console.WriteLine(b);

produces 2.0

1
ответ дан 24 November 2019 в 16:27
поделиться

Я обнаружил, что могу «подделать» шкалу, умножая или деля на причудливую 1.

decimal a = 2m;
decimal c = 2.00000000m;
decimal PreciseOne = 1.000000000000000000000000000000m;
  //add maximum trailing zeros to a
decimal x = a * PreciseOne;
  //remove all trailing zeros from c
decimal y = c / PreciseOne;

Я могу изготовить достаточно точную единицу, чтобы изменять масштабные коэффициенты на известные размеры.

decimal scaleFactorBase = 1.0m;
decimal scaleFactor = 1m;
int scaleFactorSize = 3;

for (int i = 0; i < scaleFactorSize; i++)
{
  scaleFactor *= scaleFactorBase;
}

decimal z = a * scaleFactor;
]
5
ответ дан 24 November 2019 в 16:27
поделиться

It's tempting to confuse decimal in SQL Server with decimal in .NET; they are quite different.

A SQL Server decimal is a fixed-point number whose precision and scale are fixed when the column or variable is defined.

A .NET decimal is a floating-point number like float and double (the difference being that decimal accurately preserves decimal digits whereas float and double accurately preserve binary digits). Attempting to control the precision of a .NET decimal is pointless, since all calculations will yield the same results regardless of the presence or absence of padding zeros.

5
ответ дан 24 November 2019 в 16:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: