Cipher
Cipher

Reputation: 6082

Restricting the number of digits after decimal

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?

Upvotes: 0

Views: 3142

Answers (5)

chanakya
chanakya

Reputation: 29

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;

Upvotes: 0

Heinzi
Heinzi

Reputation: 172220

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.

Upvotes: 0

Scott Weaver
Scott Weaver

Reputation: 7351

regex is always the answer ;)

var n = Regex.Replace(convertedToSingle.ToString(), @"([^.]*\.\d{0,3}).*", "$1");

Upvotes: -1

dimoss
dimoss

Reputation: 1506

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));

Upvotes: 1

Coder
Coder

Reputation: 896

maybe you can try this

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

Upvotes: 1

Related Questions