PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] What is the minimum decimal which can be converted to float and then back to decimal?

 August 07, 2022     c#, converters, decimal, floating-point, precision     No comments   

Issue

var t = (decimal)((float)decimal.MinValue)

fails with error CS0031: Constant value '-7.922816E+28' cannot be converted to a 'decimal', but why?

decimal.MinValue is -79228162514264337593543950335m. It successfully converts to float as -79228160000000000000000000000f wichh is larger than decimal.MinValue:

(float)decimal.MinValue > decimal.MinValue

Why this value can't be converted? I understand it's something about the significand and the exponent but what exactly happen? And which is minimum decimal which can be converted to float and then back to decimal in C#?


Solution

You are not printing the full precision of the float, so you cannot see the value that is causing it to fail.

If you change the code as follows:

var decMin = (float)decimal.MinValue;
Console.WriteLine(decMin.ToString("R")); // "-7.9228163E+28"

// Next line throws System.OverflowException: Value was either too large or too small for a Decimal.
var dec = (decimal)decMin; 

The value of decMin is displayed as -7.9228163E+28. To make this easier to compare, let's rewrite that without the exponent and compare it to decimal.MinValue:

decMin           = -79_228_163_000_000_000_000_000_000_000
decimal.MinValue = -79_228_162_514_264_337_593_543_950_335

Now you can see that decMin is MORE NEGATIVE than decimal.MinValue - which explains why it fails to convert.



Answered By - Matthew Watson
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing