[英]Float to Decimal Conversion in C#
int i = 1; // -2,147,483,648 to 2,147,483,647
float f = 2.1f; // -3.402823e38 to 3.402823e38
long l = 3; // -922337203685477508 to 922337203685477507
double dbl = 4.5; // -1.79769313486232e308 to 1.79769313486232e308
decimal dec = 5.2m; // -79228162514264337593543950335 to 79228162514264337593543950335
dec = i; // No error
dec = l; // No error
dec = f; // Compiler error
dec = dbl; // Compiler error
f = (float)dec; // No error (May loss precision) ok
**dec = (decimal)dbl;** // No error why it requires ?
Why the above code requires Explicit Cast. 为什么上述代码需要Explicit Cast。 Range of float/Double > Decimal ? 浮点/双精度范围>十进制?
Because it isn't just about precision; 因为这不仅仅是精度; you need to think about range too - and frankly 1.79769313486232e308
is really, really large (as in > 300 digits to the left of the decimal place). 您还需要考虑范围 -坦率地说, 1.79769313486232e308
确实非常大(如小数点左边的300位数以上)。 Your assertion "Even Range of decimal > float or double" is incorrect. 您的断言“偶数范围>浮点数或双精度数”是错误的。
var dbl = double.MaxValue;
var dec = (decimal) dbl; // BOOM!
The range of a double
is larger than the range of a decimal
. double
的范围大于 decimal
的范围。
Also, you might need to consider double.NaN
, double.PositiveInfinity
and double.NegativeInfinity
. 另外,您可能需要考虑double.NaN
, double.PositiveInfinity
和double.NegativeInfinity
。
I believe the Conversion depends on the size of the datatype not on the Range of the Datatype. 我相信转换取决于数据类型的大小,而不取决于数据类型的范围。
Integral Types
DataType Size . Net (CTS) Comments
byte 1 System.Byte 0 - 255 It is Unsigned
sbyte 1 System.SByte -128 to 127 - Signed
short 2 System.Int16
ushort 2 System.UInt16
int 4 System.Int32
uint 4 System.Unt32
long 8 System.Int64
ulong 8 System.UInt64
Floating Types
decimal 16 System.Decimal Has up to 28 digits after decimal
float 4 System.Single Has up to 8 digits after decimal
double 8 System.Double Has up to 15 digits after decimal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.