Click here to Skip to main content
15,901,373 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,

having a decimal dynamic value, which dynamically i want to display the last 2 digits of the decimal value such as 0.12289 and 1.23564875 and so on. want to display 0.89 and 1.75

Long life for Code Project Members.

Thanks in advance.
Posted

An alternative using Regex is as follows:

C#
double num = 1.23564875;
string numString = Regex.Replace(num.ToString("R"),@"(?<=\d*\.)\d*(?=\d{2})","");
Console.WriteLine (numString);

//Output
//1.75
 
Share this answer
 
Comments
Shahin Khorshidnia 27-May-12 13:02pm    
Good solution. My + FIVE
VJ Reddy 30-May-12 7:47am    
Thank you, Shahin :)
Try this:

C#
string s = "0.12289";
string[] words = s.Split(".");
string result=words[0]+"."+words[1].Substring (words[1].Length-2);
 
Share this answer
 
Dirty, but working for both of your test cases:
C#
double d = 0.12289;
string ds = d.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
int s = (ds.IndexOf(".") + 1);
int l = ((ds.Length) - s);
string sout = ds.Substring(0, s) + ds.Substring(s+l-2, 2);
MessageBox.Show(sout);
 
Share this answer
 
call the function getamount for your problem it will return your desired result
C#
protected void Page_Load(object sender, EventArgs e)
    {
        double dec1 = 1.23564875;
        TextBox1.Text = GetAmount(dec1);
    }

private string GetAmount(double amount)
    {
        string[] str = amount.ToString().Split('.');

        string str1 = str[0];
        string str2 = str[1];
        string str3 = str2.Substring(str2.Length - 2);
        return str1 + "." + str3;

    }
 
Share this answer
 
v2
Thanks from all of you guys.
i solve my problem in the following way.it works well.

C#
double _val = 0.12121219;
            textBox1.Text = _val.ToString("0.##");
 
Share this answer
 
Consider using Math.Round[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900