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?
maybe you can try this
nnuma.ToString ("#.###");
numb.ToString ("#.###");
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));
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;
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 decimal
s as an alternative, if decimal precision is an issue.
Note that this overload of Math.Round
performs Banker's Rounding , ie, 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.
正则表达式始终是答案;)
var n = Regex.Replace(convertedToSingle.ToString(), @"([^.]*\.\d{0,3}).*", "$1");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.