Get the decimal part from a double

后端 未结 18 849
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  -上瘾入骨i
    2020-11-29 07:47

    Updated Answer

    Here I am giving 3 approaches for the same.

    [1] Math Solution using Math.Truncate

     var float_number = 12.345;
     var result = float_number - Math.Truncate(float_number);
    

    // input : 1.05
    // output : "0.050000000000000044"

    // input : 10.2
    // output : 0.19999999999999929

    If this is not the result what you are expecting, then you have to change the result to the form which you want (but you might do some string manipulations again.)

    [2] using multiplier [which is 10 to the power of N (e.g. 10² or 10³) where N is the number of decimal places]

           // multiplier is " 10 to the power of 'N'" where 'N' is the number 
           // of decimal places
           int multiplier = 1000;  
           double double_value = 12.345;
           int double_result = (int)((double_value - (int)double_value) * multiplier);
    

    // output 345

    If the number of decimal places is not fixed, then this approach may create problems.

    [3] using "Regular Expressions (REGEX)"

    we should be very careful while writing solutions with string. This would not be preferable except some cases.

    If you are going to do some string operations with decimal places, then this would be preferable

        string input_decimal_number = "1.50";
        var regex = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
        if (regex.IsMatch(input_decimal_number))
        {
            string decimal_places = regex.Match(input_decimal_number).Value;
        }
    

    // input : "1.05"
    // output : "05"

    // input : "2.50"
    // output : "50"

    // input : "0.0550"
    // output : "0550"

    you can find more about Regex on http://www.regexr.com/

提交回复
热议问题