-1

Decimal Value is 12568.521 When converting into float (float)Value

Value is coming as 12568.5215. I need exact value as 12568.521. Please anyone guide me.

  • Can you please share the converting code? – Athanasios Kataras Feb 11 '21 at 07:27
  • 1
    There isn’t enough precision. This isn’t rounding, just the basic way floats work. Doubles would be able to handle it – Sami Kuhmonen Feb 11 '21 at 07:33
  • 1
    You can't. The precision of the `float` type is just not big enough to hold exaclty that value. If you need an exact number of decimal places, you should use the `decimal` type. That's the purpose of the decimal type – derpirscher Feb 11 '21 at 07:34
  • 2
    Does this answer your question? [Why are floating point numbers inaccurate?](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – Drag and Drop Feb 11 '21 at 07:36
  • 1
    Question boils down to, "*if i tip a big bucket of water into a little bucket, I don't have the same amount of water*" , "*I need exact value*" - Sorry you are out of luck, that's not how floating point values work – TheGeneral Feb 11 '21 at 07:39

2 Answers2

-1

Try using Round in Math

decimal value = 12568.5215;
return Math.Round(value,3);
  • Watch out, `12568.5215` is a constant of type `double`. Add an "m" suffix to make it decimal: `12568.5215m` – Hans Kesting Feb 11 '21 at 07:36
  • First of all, your syntax is invalid. To assign a number literal to a decimal variable you have to use `decimal value = 12346.324M;` Second, there is no overload of `Math.round()`, that accepts a `decimal` as first parameter. – derpirscher Feb 11 '21 at 07:37
-1

You may convert the decimal variable into a string:

decimal d = new decimal(12568.521);
float f = Single.Parse(d.ToString());