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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With