Get the decimal part from a double

后端 未结 18 850
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 06:47

I want to receive the number after the decimal dot in the form of an integer. For example, only 05 from 1.05 or from 2.50 only 50 not 0.50

18条回答
  •  醉梦人生
    2020-11-29 07:50

    Solution without rounding problem:

    double number = 10.20;
    var first2DecimalPlaces = (int)(((decimal)number % 1) * 100);
    Console.Write("{0:00}", first2DecimalPlaces);
    

    Outputs: 20

    Note if we did not cast to decimal, it would output 19.

    Also:

    • for 318.40 outputs: 40 (instead of 39)
    • for 47.612345 outputs: 61 (instead of 612345)
    • for 3.01 outputs: 01 (instead of 1)

    If you are working with financial numbers, for example if in this case you are trying to get the cents part of a transaction amount, always use the decimal data type.

    Update:

    The following will also work if processing it as a string (building on @SearchForKnowledge's answer).

    10.2d.ToString("0.00", CultureInfo.InvariantCulture).Split('.')[1]
    

    You can then use Int32.Parse to convert it to int.

提交回复
热议问题