C# get digits from float variable

前端 未结 12 1676
南笙
南笙 2020-12-06 16:26

I have a float variable and would like to get only the part after the comma, so if I have 3.14. I would like to get 14 as an integer. How can I do that?

12条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 17:22

    using Regular Expressions (REGEX)

    string input_decimal_number = "3.14";
    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 : "3.14"
    // output : "14"

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

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

    Math Solution using Math.Truncate

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

    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

提交回复
热议问题