-1

I want to display only tenths of decimal.

decimal d = 44.22m;

var s = d.ToString("");

How to make this s == "22" true ?

PS: i'm well aware i can do some math but i'm want to display tenths in WPF using only Binding and StringFormat

King King
  • 61,710
  • 16
  • 105
  • 130
Dejan Dakić
  • 2,418
  • 2
  • 25
  • 39

4 Answers4

0

It is not the best but it works :

        decimal d = 44.22m;
        string ds = d.ToString().Remove(0, (d.ToString().IndexOf(',') + 1));
jd6
  • 429
  • 3
  • 9
0
decimal d = 44.22m;

Regex regex = new Regex(@"\d*(?=m)");
Match match = regex.Match(d);
if (match.Success)
{
        Console.WriteLine(match.Value);
}
MadsDue
  • 47
  • 3
0

If you need a lot of operations, maybe set up a function for this step!? I guess using String.Format only wouldnt work.

int getDecimals (decimal d)
{
    try
    {
        int s = Convert.ToInt32(string.Format("{0}", d.ToString().Split('.')[1]));
        return s;
    }
    catch { //whatever u want// }
}

// ==> //

decimal d = 44.22m;

string s = getDecimals(d).ToString();
C4d
  • 3,183
  • 4
  • 29
  • 50
0

There is an answer posted for a similar question here.

https://stackoverflow.com/a/19374418/4101237

posted by user https://stackoverflow.com/users/2608383/karthik-krishna-baiju

Original Post Code:

string outPut = "0";
if (MyValue.ToString().Split('.').Length == 2)
{
outPut = MyValue.ToString().Split('.')[1].Substring(0, MyValue.ToString().Split('.')[1].Length);
}
Console.WriteLine(outPut);

Modified to your requirements:

decimal d = 44.22m;
string outPut = "0";
if (d.ToString().Split('.').Length == 2)
{
    outPut = d.ToString().Split('.')[1].Substring(0, d.ToString().Split('.')[1].Length);
}
Console.WriteLine(outPut);

--input samples--
1) 46.0
2) 46.01
3) 46.000001
4) 46.1 5) 46.12
6) 46.123
7) 46.1234

--outputs--
1) 0
2) 01
3) 000001
4) 1
5) 12
6) 123
7) 1234

Community
  • 1
  • 1
peege
  • 2,467
  • 1
  • 10
  • 24