C# 从 double 中获取小数部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13038482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:25:36  来源:igfitidea点击:

Get the decimal part from a double

c#.net

提问by user1095549

I want to receive the number after the decimal dot in the form of an integer. For example, only 05 from 1.05 or from 2.50 only 50 not0.50

我想以整数的形式接收小数点后的数字。例如,只有 05 从 1.05 或从 2.50 只有 50而不是0.50

采纳答案by Karthik Krishna Baiju

Updated Answer

更新答案

Here I am giving 3 approaches for the same.

在这里,我给出了 3 种相同的方法。

[1] Math Solution using Math.Truncate

[1] 使用Math.Truncate 的数学解决方案

 var float_number = 12.345;
 var result = float_number - Math.Truncate(float_number);

// input : 1.05
// output : "0.050000000000000044"

// 输入:1.05
// 输出:“0.050000000000000044”

// input : 10.2
// output : 0.19999999999999929

// 输入:10.2
// 输出:0.19999999999999929

If this is not the result what you are expecting, then you have to change the result to the form which you want (but you might do some string manipulations again.)

如果这不是您所期望的结果,那么您必须将结果更改为您想要的形式(但您可能会再次进行一些字符串操作。)

[2] using multiplier [which is 10 to the power of N (e.g. 102 or 103) where N is the number of decimal places]

[2] 使用乘数 [这是 10 的 N 次方(例如 102 或 103),其中 N 是小数位数]

       // multiplier is " 10 to the power of 'N'" where 'N' is the number 
       // of decimal places
       int multiplier = 1000;  
       double double_value = 12.345;
       int double_result = (int)((double_value - (int)double_value) * multiplier);

// output 345

// 输出 345

If the number of decimal places is not fixed, then this approach may create problems.

如果小数位数不固定,则此方法可能会产生问题。

[3] using "Regular Expressions (REGEX)"

[3] 使用“正则表达式(REGEX)”

we should be very careful while writing solutions with string. This would not be preferableexcept some cases.

我们在用字符串编写解决方案时应该非常小心。除某些情况外,这不是可取的

If you are going to do some string operations with decimal places, then this would be preferable

如果您要进行一些带小数位的字符串操作,那么这将是可取的

    string input_decimal_number = "1.50";
    var regex = new System.Text.RegularExpressions.Regex("(?<=[\.])[0-9]+");
    if (regex.IsMatch(input_decimal_number))
    {
        string decimal_places = regex.Match(input_decimal_number).Value;
    }

// input : "1.05"
// output : "05"

// 输入:“1.05”
// 输出:“05”

// input : "2.50"
// output : "50"

// 输入:“2.50”
// 输出:“50”

// input : "0.0550"
// output : "0550"

// 输入:“0.0550”
// 输出:“0550”

you can find more about Regex on http://www.regexr.com/

您可以在http://www.regexr.com/上找到有关 Regex 的更多信息

回答by tmesser

var decPlaces = (int)(((decimal)number % 1) * 100);

This presumes your number only has two decimal places.

这假设您的数字只有两位小数。

回答by System Down

var result = number.ToString().Split(System.Globalization.NumberDecimalSeparator)[2]

Returns it as a string (but you can always cast that back to an int), and assumes the number does have a "." somewhere.

将其作为字符串返回(但您始终可以将其转换回 int),并假设该数字确实有一个“。” 某处。

回答by swabs

Use a regex: Regex.Match("\.(?\d+)")Someone correct me if I'm wrong here

使用正则表达式:Regex.Match("\.(?\d+)")如果我在这里错了,有人会纠正我

回答by Parag Meshram

Better Way -

更好的方法 -

        double value = 10.567;
        int result = (int)((value - (int)value) * 100);
        Console.WriteLine(result);

Output -

输出 -

56

回答by Picrofo Software

You may remove the dot .from the double you are trying to get the decimals from using the Remove()function after converting the double to string so that you could do the operations required on it

.在将双精度Remove()转换为字符串后,您可以从尝试使用该函数获取小数的双精度中删除点,以便您可以对其进行所需的操作

Consider having a double _Doubleof value of 0.66781, the following code will only show the numbers after the dot .which are 66781

考虑有一个 double_Double的值0.66781,下面的代码将只显示点.后面的数字66781

double _Double = 0.66781; //Declare a new double with a value of 0.66781
string _Decimals = _Double.ToString().Remove(0, _Double.ToString().IndexOf(".") + 1); //Remove everything starting with index 0 and ending at the index of ([the dot .] + 1) 

Another Solution

另一种解决方案

You may use the class Pathas well which performs operations on string instances in a cross-platform manner

您也可以使用Path以跨平台方式对字符串实例执行操作的类

double _Double = 0.66781; //Declare a new double with a value of 0.66781
string Output = Path.GetExtension(D.ToString()).Replace(".",""); //Get (the dot and the content after the last dot available and replace the dot with nothing) as a new string object Output
//Do something

回答by Berezh

    public static string FractionPart(this double instance)
    {
        var result = string.Empty;
        var ic = CultureInfo.InvariantCulture;
        var splits = instance.ToString(ic).Split(new[] { ic.NumberFormat.NumberDecimalSeparator }, StringSplitOptions.RemoveEmptyEntries);
        if (splits.Count() > 1)
        {
            result = splits[1];
        }
        return result;
    }

回答by matterai

the best of the best way is:

最好的方法是:

var floatNumber = 12.5523;

var x = floatNumber - Math.Truncate(floatNumber);

result you can convert however you like

结果你可以随意转换

回答by redditmerc

int last2digits = num - (int) ((double) (num /  100) * 100);

回答by ?a?atay Yap?c?

It is very simple

这很简单

       float moveWater =  Mathf.PingPong(theTime * speed, 100) * .015f;
       int    m = (int)(moveWater);
       float decimalPart= moveWater -m ;

       Debug.Log(decimalPart);