Convert type string <--> decimal

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace Test
{
    class Program
    {

        private static decimal ToDecimal(string Value)
        {
            if (string.IsNullOrEmpty(Value))
                return 0;
            else
            {

                try
                {
                    //sử dụng dạng 1,123.45
                    return Decimal.Parse(Value.Replace(" ", ""), NumberStyles.AllowThousands | 
                                            NumberStyles.AllowDecimalPoint | 
                                            NumberStyles.AllowCurrencySymbol,                        
                                            CultureInfo.CreateSpecificCulture("en-us"));
                }
                catch
                {
                    try
                    {
                        //sử dụng dạng 1.123,45
                        return Decimal.Parse(Value.Replace(" ", ""), NumberStyles.AllowThousands |
                                                NumberStyles.AllowDecimalPoint |
                                                NumberStyles.AllowCurrencySymbol,
                                                CultureInfo.CreateSpecificCulture("nl-NL"));
                    }
                    catch {
                        // còn nếu mà không được thì đó không phải là chuỗi số
                        return 0;
                    }
                }

            }
        }
        private static string fDecToStr(decimal dec)
        {
            return fDecToStr(dec, ",", 0, string.Empty);
        }
        private static string fDecToStr(decimal dec, string strDauHangTram)
        {
            return fDecToStr(dec, strDauHangTram, 0, string.Empty);
        }
        private static string fDecToStr(decimal dec, string strDauHangTram, int intDauThapPhan)
        {
            return  fDecToStr(dec, strDauHangTram, intDauThapPhan , string.Empty);
        }

        private static string fDecToStr(decimal dec, string strDauHangTram, int intDauThapPhan , string dtrHauTo)
        {

            string strFormat;
            strFormat = "#,###";
            for (int i = 0; i < intDauThapPhan; i++)
            {
                if (strFormat.EndsWith("#,###"))
                    strFormat += ".";
                strFormat += "#";

            }


            //sử dụng dạng 1,123
            if (strDauHangTram.Equals(","))
                return dec.ToString(strFormat, CultureInfo.CreateSpecificCulture("en-us"));

            return dec.ToString(strFormat, CultureInfo.CreateSpecificCulture("nl-NL"));

        }
        private static string fIntToStr(int Value)
        {
            return fIntToStr(Value, ",");
        }
        private static string fIntToStr(int Value, string strDauHangTram)
        {
            //sử dụng dạng 1,123
            if (strDauHangTram.Equals(","))
                return Value.ToString("#,###.", CultureInfo.CreateSpecificCulture("en-us"));

            return Value.ToString("#,###.", CultureInfo.CreateSpecificCulture("nl-NL"));

        }


        static void Main(string[] args)
        {
            string a;
            a = "1115.45.4545,25201";
            decimal dec;
            dec = ToDecimal(a);


            Console.WriteLine(dec.ToString("#,###", CultureInfo.CreateSpecificCulture("nl-NL")));
            Console.WriteLine(dec.ToString("#,###", CultureInfo.CreateSpecificCulture("en-us")));

            Console.WriteLine("===============");
            Console.WriteLine(fDecToStr(dec, ".", 3, string.Empty));
            Console.WriteLine(fDecToStr(dec, ",", 5, string.Empty));

            Console.WriteLine("===============");
        }
    }
}

Convert String To Decimal

private decimal ToDecimal(string Value)
{
 if (Value.Length == 0)
                return 0;
        else
                return Decimal.Parse(Value.Replace(" ", ""), NumberStyles.AllowThousands 
   | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol);
}

String Format for Int [C#]

Integer numbers can be formatted in .NET in many ways. You can use static method String.Format or instance method int.ToString. Following examples shows how to align numbers (with spaces or zeroes), how to format negative numbers or how to do custom formatting like phone numbers.

Add zeroes before number

To add zeroes before a number, use colon separator „:“ and write as many zeroes as you want.

 

String.Format("{0:00000}", 15);          // "00015"
String.Format("{0:00000}", -15);         // "-00015"

 

Align number to the right or left

To align number to the right, use comma „,“ followed by a number of characters. This alignment option must be before the colon separator.

 

String.Format("{0,5}", 15);              // "   15"
String.Format("{0,-5}", 15);             // "15   "
String.Format("{0,5:000}", 15);          // "  015"
String.Format("{0,-5:000}", 15);         // "015  "

 

Different formatting for negative numbers and zero

You can have special format for negative numbers and zero. Use semicolon separator „;“ to separate formatting to two or three sections. The second section is format for negative numbers, the third section is for zero.

 

String.Format("{0:#;minus #}", 15);      // "15"
String.Format("{0:#;minus #}", -15);     // "minus 15"
String.Format("{0:#;minus #;zero}", 0);  // "zero"

 

Custom number formatting (e.g. phone number)

Numbers can be formatted also to any custom format, e.g. like phone numbers or serial numbers.

 

String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551);       // "89-5871-2551"

 

String Format for Double [C#]

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.

Digits after decimal point

This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.

 

// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.

// max. two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"

Digits before decimal point

If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.

// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567);      // "123.5"
String.Format("{0:00.0}", 23.4567);       // "23.5"
String.Format("{0:00.0}", 3.4567);        // "03.5"
String.Format("{0:00.0}", -3.4567);       // "-03.5"

 

Thousands separator

To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.

 

String.Format("{0:0,0.0}", 12345.67);     // "12,345.7"
String.Format("{0:0,0}", 12345.67);       // "12,346"

 

Zero

Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).

Following code shows how can be formatted a zero (of double type).

 

String.Format("{0:0.0}", 0.0);            // "0.0"
String.Format("{0:0.#}", 0.0);            // "0"
String.Format("{0:#.0}", 0.0);            // ".0"
String.Format("{0:#.#}", 0.0);            // ""

 

Align numbers with spaces

To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.

 

String.Format("{0,10:0.0}", 123.4567);    // "     123.5"
String.Format("{0,-10:0.0}", 123.4567);   // "123.5     "
String.Format("{0,10:0.0}", -123.4567);   // "    -123.5"
String.Format("{0,-10:0.0}", -123.4567);  // "-123.5    "

Custom formatting for negative numbers and zero

If you need to use custom format for negative float numbers or zero, use semicolon separator;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.

 

String.Format("{0:0.00;minus 0.00;zero}", 123.4567);   // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567);  // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0);        // "zero"

Some funny examples

As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.

String.Format("{0:my number is 0.0}", 12.3);   // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3);          // "12aaa.bbb3"