2

I am having a value like below :

decimal val = 1.100;

Now what I am trying to do is if I am having 0 after first decimal point value then I want to take only 1.1 and ignore rest and if I am having 1.11 then I want to take whole 1.11

This is how I am thinking to do it:

  1. Convert decimal to string.

  2. Split string by dot.

  3. Check if length is 2 and if second position is greater than 0 then take whole like 11 for decimal value 1.11 else if decimal is like this 1.10 then take 1.1 else take 1.0 in case of decimal 1.000

Sample input and output:

1.000 // output 1.0
1.100 // output 1.1
1.110 // output 1.11
1.111 // output 1.111
1.102 // output 1.102

But this is dirty logic which I want to avoid. Isn't there is any inbuilt way or better way to do this?

Note: I don't want to do any kind of round up.

halfer
  • 19,824
  • 17
  • 99
  • 186
I Love Stackoverflow
  • 6,738
  • 20
  • 97
  • 216

2 Answers2

5

You can use a custom numeric format string:

val.ToString("0.0##")
Sefe
  • 13,731
  • 5
  • 42
  • 55
0

Hope you like this logic. Please try this.

  double val = 1.002;
  string output = !val.ToString().TrimEnd('0').Contains('.') ? string.Format("{0}.0", val) : val.ToString().TrimEnd('0');

If the value is 1.00, then my output will be 1.0

Then you can convert this string into other data types.

Raj De Inno
  • 1,092
  • 2
  • 14
  • 33