C#得到浮点型变量的数字 [英] C# get digits from float variable

查看:271
本文介绍了C#得到浮点型变量的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮动的变量,并想在逗号后只得到了一部分,所以如果我有3.14。我想获得14为整数。我该怎么办呢?

I have a float variable and would like to get only the part after the comma, so if I have 3.14. I would like to get 14 as an integer. How can I do that?

推荐答案

的作弊方式来做到这一点是:

The cheating way to do it is:

    private Int32 FractionalPart(double n)
    {
        string s = n.ToString("#.#########", System.Globalization.CultureInfo.InvariantCulture);
        return Int32.Parse(s.Substring(s.IndexOf(".") + 1));
    }

EDIT2:OK OK OK OK。这里是最偏执永远不会失败的版本,我可以拿出。这将返回第9位(或更少,如果有没有那么多)的浮点数的小数部分。这是保证不会溢出一个Int32。我们使用不变的文化,让我们知道,我们可以用一个句点作为小数点分隔符。

edit2: OK OK OK OK. Here is the most paranoid never fail version I can come up with. This will return the first 9 digits (or less, if there aren't that many) of the decimal portion of the floating point number. This is guaranteed to not overflow an Int32. We use the invariant culture so we know that we can use a period as the decimal separator.

这篇关于C#得到浮点型变量的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆