四舍五入长小数点
我不知道正确的术语来解释这一点,我有个十进制数字从一个API,它看起来像回来:四舍五入长小数点
我不在小数点后面不需要任何数据,在上面的例子中它只是我需要的值,我可以用正则表达式来处理它,但它看起来有点混乱,任何帮助将不胜感激!
标题建议四舍五入,但你说的是四舍五入。这里有一些选项:
如果它是一个字符串,你只想要22(舍入,不上),那么使用IndexOf是最快的。这个工程预期与底片太:
string theNumber = "22.7685857856";
int pointLocation = theNumber.IndexOf('.');
int theRoundedDownNumber = int.Parse(theNumber.Substring(0,pointLocation)); // 22
如果它不是一个字符串 - 即你已经有了一个double
,float
或Decimal
,那么这些都是更好的(我假设你实际上采用双,而在这里比 '小数' 数据类型;功能是相同的或者然而方式):
为了完善向上(22.77 - > 23):
double yourNumber = 22.7685857856;
yourNumber = Math.Ceiling(yourNumber);
为了完善向下(22.77 - > 22):
double yourNumber = 22.7685857856;
yourNumber = Math.Floor(yourNumber);
要刚轮它(22.77 - > 23; 22.4 - > 22):
double yourNumber = 22.7685857856;
yourNumber = Math.Round(yourNumber);
如果你的号码是一个字符串(“22。7685857856" ),但你想使用这些功能,那么你就需要先分析它:
double yourNumber = double.Parse("22.7685857856");
(或者double.TryParse)
然而,如果你的号可以包含底片,然后事情变得有趣,因为地板和天花板会“走错路”为负数向下舍入(楼),其铸造成整数的是,围绕着一个简单的方法:
double yourNumber = 22.7685857856;
// -22.4 -> -22 and 22.4 -> 22
int yourNumberInt = (int)yourNumber;
四舍五入最安全的路线是a n如果:
if(yourNumber > 0)
{
// 22.7 -> 23
yourNumber = Math.Ceiling(yourNumber);
}
else
{
// -22.4 -> -23
yourNumber = Math.Floor(yourNumber);
}
最简单的方法使用铸造?
int x = (int) 22.7685857856;
或者,如果你只是想去掉小数位:
decimal y = Decimal.Floor(22.7685857856m);
或者,如果你想圆正确并返回string
:
string result = 22.7685857856m.ToString("N0");
有几种方法来做这个。一种方法是使用`string.split('。')[0])来获取小数点左边的字符串部分,然后将其转换为整数。
string s = "22.77";
int x = Convert.ToInt32(s.Split('.')[0]);
另一种方法是使用Math.Floor,但这样做有点混乱,因为它返回一个类型decimal
,你可能想再次转换为int
。
string s = "22.77";
int x = Convert.ToInt32(Math.Floor(Convert.ToDecimal(s)));
编辑:其实,你可能想避开第二种方法,因为Math.Floor
始终几轮下来,而不是小数点后刚刚丢弃的数字。这意味着22.77下降到22.0,但-22.77下降到-23.0。
你想四舍五入吗,还是你想要整数截断?对于整数截断 - 请参阅下面的凯文的答案。 – EtherDragon
您提到了十进制数字,但未提及该值是字符串还是小数。你看到https://msdn.microsoft.com/en-us/library/bb397679.aspx – randominstanceOfLivingThing
@EtherDragon对我来说,它看起来像整数截断,因为给出的例子 –