简体   繁体   中英

How can I convert string to decimal with trailing zero(s)

Suppose that we have stringvalue=125.32600 when it convert to decimal value with this code

decimal d;
decimal.tryparse(stringvalue,out d)

d value is 125.326 how can I do this convert with final result 125.32600

You cannot because 125.32600 is equal to 125.326 . In this case however I guess that you want to print it out with specific format, which can be done like this:

Console.WriteLine(d.ToString("f5"));

Read Standard Numeric Format Strings

UPDATE

Extension method:

public string Format(this decimal source, int precision)
{
    if (precision < 0)
    {
        throw new ArgumentOutOfRangeException("Precision must be a non negative integer");
    }

    return source.ToString("f" + precision);
}

which can be used like this:

Console.WriteLine(d.Format(5));

The answer is: You can't, at least not like that.

EDIT: correction: decimal already works like that; but you'll still find below a useful way to store your decimals in a DB.

Why? Because that's not how decimals are stored in memory.

Solution: if you need to keep the trailing zeros, just remember the precision explicitly in a separate field (of a class you should create for this purpose); or store the decimals in string form and only convert to decimal as needed.

string strValue = "125.32600";
int precision = strValue.Length - 1;  // only the "12332600" part
decimal value = Decimal.Parse(strValue);

stores 8 in precision and 125.326 in value .

To get back the original form:

int afterPt = precision - ((int) value).ToString().Length;
Console.WriteLine(value.ToString("f" + afterPt));

prints

125.32600

PS you have to be aware of floating point binary representation issues though, so stuff like 4.05 might be stored as eg 4.049999999999999999 , so if you need to guarantee this won't happen, use an algorithm that bypasses decimal altogether and uses only integers for storage and computation.

string strValue = "125.32600";

// parse and store
int value = int.Parse(strValue.Replace(".", ""));
int periodIx = strValue.IndexOf(".");

// get back the original representation
string str = value.ToString();
Console.WriteLine(str.Substring(0, periodIx) + "." + str.Substring(periodIx, str.Length - periodIx));

NOTE: Make sure to use , instead of . in locales that need it.

Your code works as written (as long as the decimal separator matches your culture):

decimal d;
decimal.TryParse("125.32600", NumberStyles.Number, CultureInfo.InvariantCulture, out d);
s = d.ToString(CultureInfo.InvariantCulture); // 125.32600

Decimal already remembers how many trailing zeros it has. This is caused by decimal representing numbers in non-normalized form, with an integer mantissa and an exponent representing the number of decimal digits. eg 125.32600 is represented as 12532600 * 10^-5

What you can do is count the zeroes in string and then store them in separate DB field. When you want the result with zeroes just concatenate the same no. of zeroes into decimal number string .

ex.

string p="123.456000";
int zeroes=p.Split('0').Length - 1; // guess
decimal value = Decimal.Parse(p); //without zeroes
string valWithZero=value.toString().padRight(zeroes,'0'); //with zeroes

If you really want to have the zeros in the database you could save it as a string, preformatted, but that would be very inefficient.

What is the problem you try to solve by this, there might be a better solution?

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