1

I want to check if a decimal has a value in the 4th significant figure.

//3 Significant figures
var val = 1.015;

//4 Significant figures
var val2 = 1.0155;

How can I test to see when there is a value in the 4th significant place.

I want to conditionaly display 3 or 4 decimal places depending if there is a non zero value in the 4th place.

What is the best way to do this?

Would this method work?

if((val * 10000) % 10 != 0) ...
ojhawkins
  • 3,200
  • 15
  • 50
  • 67

4 Answers4

1

1.Multiply the value with 1000 and then do (value%10) mod 10 for getting last digit in 3rd significant value .

Example : (3rd significant)

        var val = 1.015;
        int val1=Convert.ToInt32(val * 1000);
        Console.WriteLine(val1 %10); 

Output: 5

2.Multiply the value with 10000 and then do (value%10) mod 10for getting last digit in 4 significant value

Example : (4th significant)

        var val = 1.0157;
        int val1=Convert.ToInt32(val * 10000);
        Console.WriteLine(val1 %10);

Output: 7
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
1

To learn about formatting your output check this out http://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx

To just check if there are 4 or more significant digits you can do

 if (inputString.Split('.')[1].Length > 3)

Of course, that isn't doing any error checking an could easily throw some exceptions but no need to clutter my answer with some basic bounds and nullity checks.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
1

You can do this with a custom format string:

double d = 1.2340;
string strDouble = d.ToString("0.000#");
MarkPflug
  • 28,292
  • 8
  • 46
  • 54
0

The silly answer would be: find the location of the . in your string, and then check the location+4.

The more serious would be, have a look at the double formatting options :)

You could use this formatting of double

//       using the   F4:                    1054.3224

and then if the last index of your string is 0, cut it out using substring.


As of your last edit (if((val * 10000) % 10 != 0) ...), yes, it should work ... Sudhakar suggested the same in his answer.

You should probably take whichever solution you go with, and put it in a helper method that returns an int, and then you can just use that in your code, helping your readability, and reusalibilyt :)


Go with Marks solution, simplest I guess.

double d = 3.40;
Console.Out.WriteLine("d 0.0: {0}", d);                     // 3.4
Console.Out.WriteLine("d 0.0: {0}", d.ToString("0.0"));     // 3.4
Console.Out.WriteLine("d 0.00: {0}", d.ToString("0.00"));   // 3.40
Console.Out.WriteLine("d 0.0#: {0}", d.ToString("0.0#"));   // 3.4

Do notice that if all you have is 3 or 4 digts after the ., the default would be truncated and removed as you can see if the first output above.

Noctis
  • 11,507
  • 3
  • 43
  • 82