How do I convert the string “39.9983%” into “39%” in C#?

后端 未结 8 1044
一整个雨季
一整个雨季 2021-01-16 07:46

I don\'t want to do any rounding, straight up, \"39%\".

So \"9.99%\" should become \"9%\".

相关标签:
8条回答
  • 2021-01-16 08:17
    int.Parse("39.999%".Split('.')[0])
    

    Doing this gives you a nice int that you can work with as you see fit. You can stick a % sign on the end with whatever string concatenation floats your boat.

    0 讨论(0)
  • 2021-01-16 08:19

    I'm guessing you want a string returned? Probably the laziest way to do it:

        string mynum = "39.999%"
        mynum = mynum.substring(0, mynum.IndexOf('.'));
        mynum += "%";
        

    To get an int, you could cast the result of line 2.

    0 讨论(0)
  • 2021-01-16 08:21

    One way to do it:

    "39.999%".Split(new char[] { '.' })[0] + "%";
    
    0 讨论(0)
  • 2021-01-16 08:27
    Console.WriteLine("{0}%", (int)39.9983);
    
    0 讨论(0)
  • 2021-01-16 08:35

    Probably a Regex. I'm no master of regular expressions, I generally avoid them like the plague, but this seems to work.

    string num = "39.988%";
    string newNum = Regex.Replace(num, @"\.([0-9]+)%", "%");
    
    0 讨论(0)
  • 2021-01-16 08:37
    string myPercentage = "48.8983%";
    
    string newString = myPercentage.Replace("%","");
    
    int newNumber = (int)Math.Truncate(Double.Parse(newString));
    
    Console.WriteLine(newNumber + "%");
    

    There maybe hundred ways of doing this and this is just one :)

    0 讨论(0)
提交回复
热议问题