简体   繁体   中英

Format string with decimal

I am trying to take a string that may or may not contain a '.' to x amount of characters removing the "decimal point" as well. the result will ultimately be converted to a signed integer. I will also always need to the 1/10 decimal (ie 10 will become 100, 1 will become 10, etc...) I would like to just format the string without converting to an integer until the very end.

Example

if my incoming string is

9.86 I want 98 as a string ( i don't care about rounding up or anything)

if i get 9 I want 90

if i get -100 i want -1000

if i get -95.353 i want -953

string.Format("{0:d}", (int)9.015*10);

If you want a rounded result, replace the Cast

Edit: But I missed the "string" part. Verbose code below

var input = "9.86";
var len = input.IndexOf('.');
var result = "";
if (len > 0)
{
    result = input.Substring(0, len);
    result += input.Substring(len + 1, 1);
}
else
{
    result = input + "0";
}

If you are essentially multiplying by ten the number contained in the string and dropping decimal places after the first, then you would be better off casting the string as a decimal and then doing the conversion and casting that number as an integer. Otherwise you will have to write a large set of mathematical rules on how to modify your string based on a particular type of input.

        string[] input  = {"9.86", "9", "-100", "-95.3"};
        List<int> intNums = new List<int>();
        foreach (string s in input)
        {
            decimal number;
            if (Decimal.TryParse(s, out number))
            {
                number = number * 10;  
                intNums.Add((int)number);
            }

        }

Output: [0] 98 int [1] 90 int [2] -1000 int [3] -953 int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM