views:

641

answers:

2

Hello!

I have a problem, i didn't found yet the solution so i am asking your help. In my database I have some int, decimal and string that needs to be convert in numeric with specific length and precision to include in a flat file.

ex:

integer 123 to numeric(8,0) ==> 00000123
decimal 123,123 to numeric(8,8) ==> 0000012312300000
String "22" to numeric(8,0) ==> 00000022

It can't put comma or dot. Is there an easy solution I try a lot of things but none will give me my result except doing loops foreach Filed in my flat file too dirty!!

EDIT:

the flat file gets information based on there start point and the lenght so every data i includ in the file has to be a cetain lenght. And for the Numeric I have for exemple

   database Decimal Price = 123,456
   File     Numeric(8,6) Price = 00000123456000

I wanted to know how could i parse any decimal or integer data based on N(,)

+3  A: 

Check out String.Format:

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

Amber
+4  A: 

Try this:

string ToNumericString(int value) {
    return value.ToString("00000000");
}

string ToNumericString(decimal value) {
    var value16 = Math.Truncate(value * 100000000);
    return value16.ToString("0000000000000000");
}

string ToNumericString(string value) {
    return ToNumericString(int.Parse(value, CultureInfo.InvariantCulture));
}

To call it:

    MessageBox.Show(ToNumericString(123));
    MessageBox.Show(ToNumericString(123.123M));
    MessageBox.Show(ToNumericString("22"));

or more general:

string ToNumericString(decimal value, int digitsBefore, int digitsAfter) {
    var value16 = Math.Truncate(value * (decimal)Math.Pow(10,digitsAfter));
    return value16.ToString(new String('0', digitsBefore + digitsAfter));
}

MessageBox.Show(ToNumericString(123.123M, 8, 3));
Josip Medved
how could it put "0" befor and after my value? decimal 123,123 to numeric(8,8) ==> 0000012312300000
Polo
@Polo In example above, I did it by adding eight 0s to the number (multiply with 100000000) and then converting it to string with sixteen 0 characters. That produces desired result (test it).Other way you could do it is converting number before and after . separately. That would give you same result as first method but with little bit more clarity.
Josip Medved
I've seen your exemple but i m trying to edit it because i have to choose the lenght sometime they want an N(8,3) or N(13,0) or N(9,3)
Polo
@Polo: I added more general example.
Josip Medved
Great, that was the exact algorithme that i was looking for!!! THANKS A LOT
Polo