Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to decimal with precision and scale

Tags:

c#

.net

Is there any helper method to convert a string to a decimal setting the format dynamically?

Something like this:

var myNumber = decimal.Parse(myString, precision, scale);

eg:

myString: "0109123456"
precision: 9
scale: 6
output: 109.123456

Original problem

I am reading values from a file that have a fixed length:

Sample line:

004574575434768743486765025448754546746485678696854745646874

For that I'm using FileHelpers, but each value has a different precision/scale:

Amount1 (pos0-pos16) - precision: 15, scale: 2
Amount1 (pos17-pos25) - precision: 7, scale: 3

FileHelpers gets me the value within the range that I determined but after that I need to convert it.

like image 224
Hélder Gonçalves Avatar asked Sep 12 '25 22:09

Hélder Gonçalves


2 Answers

Quick example:

public static class stringExtension
{
    public static decimal ToDecimal(this string s, int precision, int scale)
    {
        if (s.Length < precision)
            throw new ArgumentException();
        return decimal
            .Parse(
            s.Substring(s.Length - precision)
            .Insert(precision - scale, ".")
            .ToString()
            ,
            System.Globalization.NumberStyles.AllowDecimalPoint,
            System.Globalization.NumberFormatInfo.InvariantInfo
            );
    }
}

And to use:

        string s = "0109123456";
        decimal d = s.ToDecimal(9, 6); // returns 109.123456M
like image 115
Aly Elhaddad Avatar answered Sep 15 '25 12:09

Aly Elhaddad


You could use System.Data.SqlTypes.SqlDecimal for this

System.Data.SqlTypes.SqlDecimal.ConvertToPrecScale(SqlDecimal.Parse(yourString), 9, 6); // params: SqlDecimal n, int precision, int scale

Here's the MSDN-link.

To get a decimal, you can use SqlDecimal.Value then.

Be careful if you use ConvertToPrecScale it throws a SqlTruncateException

The exception that is thrown when you set a value into a System.Data.SqlTypes

like image 22
Nitro.de Avatar answered Sep 15 '25 13:09

Nitro.de