0

For the purpose of limiting the number of digits after the decimal, I am doing the following in my webpage.

Single nnuma = Convert.ToSingle(dr["num1"].ToString());
Single numb = Convert.ToSingle(dr["num2"].ToString());

I have to restrict the number of digits after decimal to 3. How is this done here in Single data type?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Cipher
  • 5,894
  • 22
  • 76
  • 112

5 Answers5

1

maybe you can try this

nnuma.ToString ("#.###");
numb.ToString ("#.###");

Coder
  • 886
  • 1
  • 12
  • 28
1

You can try this. This will also properly precision the last digit, ie 0.6666 will be 0.667

decimal num = 20.123456789m;
Single x = Convert.ToSingle(String.Format("{0:00.000}", num));
dimoss
  • 1,506
  • 2
  • 16
  • 24
0

Very Simple. Just Write # to Restrict digits after Decimal.

num.ToString("0.0000#") -- Restrict to 4 digits;

num.ToString("0.0#")-- Restrict to 1 digit;

chanakya
  • 29
  • 1
0

The operation you are looking for is Math.Round:

Single unrounded = (Single)dr["num1"];  // change if the DB type is not a single
double rounded = Math.Round(unrounded, 3);
Single roundedSingle = (Single)rounded;

Math.Round returns a double when used with a Single, hence the need to convert to Single (float) afterwards. As a side note: You might want to consider using decimals as an alternative, if decimal precision is an issue.

Note that this overload of Math.Round performs Banker's Rounding, i.e., 0.0005 becomes 0.000, but 0.0015 becomes 0.002. If you want a different kind of rounding, use the Math.Round(Double, Int32, MidpointRounding) overload instead.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
-1

regex is always the answer ;)

var n = Regex.Replace(convertedToSingle.ToString(), @"([^.]*\.\d{0,3}).*", "$1");
Scott Weaver
  • 7,192
  • 2
  • 31
  • 43
  • apparently the wink is not enough for some people. (this does actually work, and isn't the worst way to process a string) – Scott Weaver Mar 07 '12 at 06:15