why can't you assign a number with a decimal point to decimal type directly without using type suffix?

前端 未结 5 2001
借酒劲吻你
借酒劲吻你 2021-02-02 05:40

Why can\'t you assign a number with a decimal point to the decimal type directly without using type suffix? isn\'t this kind of number considered a number of type decimal?

5条回答
  •  旧时难觅i
    2021-02-02 06:06

    Actually, hidden spec feature: you can ;-p

    decimal bankBalance = (decimal)3433.20;
    

    This is genuinely parsed by the compiler as a decimal (not a float and a cast). See the IL to prove it. Note that the precision gets truncated, though (this has 1 decimal digit, not the 2 you get from the M version).

    IL generated:

    L_0001: ldc.i4 0x861c
    L_0006: ldc.i4.0 
    L_0007: ldc.i4.0 
    L_0008: ldc.i4.0 
    L_0009: ldc.i4.1 
    L_000a: newobj instance void [mscorlib]System.Decimal::.ctor(int32, int32, int32, bool, uint8)
    L_000f: stloc.0 
    

    Compared to:

    decimal bankBalance = 3433.20M;
    

    Which generates:

    L_0001: ldc.i4 0x53d18
    L_0006: ldc.i4.0 
    L_0007: ldc.i4.0 
    L_0008: ldc.i4.0 
    L_0009: ldc.i4.2 
    L_000a: newobj instance void [mscorlib]System.Decimal::.ctor(int32, int32, int32, bool, uint8)
    L_000f: stloc.0 
    

    The only difference is the decimal digits (1 vs 2, and a factor of 10, accordingly)

提交回复
热议问题