小数ドットの後の数字を整数で受け取りたいのですが。たとえば、1.05から05のみ、または2.50から50のみ、 0.50ではありません
decimal、float、string、...?
小数ドットの後の数字を整数で受け取りたいのですが。たとえば、1.05から05のみ、または2.50から50のみ、 0.50ではありません
decimal、float、string、...?
回答:
更新された回答
ここで私は同じための3つのアプローチを与えています。
[1] Math.Truncateを使用した数学ソリューション
var float_number = 12.345;
var result = float_number - Math.Truncate(float_number);
//入力:1.05
//出力: "0.050000000000000044"
//入力:10.2
//出力:0.19999999999999929
これが期待どおりの結果でない場合は、結果を目的の形式に変更する必要があります(ただし、文字列を再度操作する場合があります)。
[2]乗数を使用する[10のN乗(例:10²または10³)。ここで、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);
//出力345
小数点以下の桁数が固定されていない場合、このアプローチは問題を引き起こす可能性があります。
[3]「正規表現(REGEX)」の使用
文字列を使用してソリューションを作成するときは、十分に注意する必要があります。これは、いくつかの場合を除いて好ましくありません。
小数点以下の桁数で文字列操作を行う場合は、これが望ましいでしょう。
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;
}
//入力: "1.05"
//出力: "05"
//入力: "2.50"
//出力: "50"
//入力: "0.0550"
//出力: "0550"
正規表現の詳細については、http://www.regexr.com/をご覧ください。
.、で分割されますが、これは必ずしも小数点記号ではありません(つまり、ヨーロッパでは小数点記号はです,)。あなたはCultureInfo.Invariantそれを国際的にするために追加しなければなりません。使用するだけの方が簡単x - Math.Truncate(x)ですが、その結果に魔法をかけますか。
最良の方法の最良は次のとおりです。
var floatNumber = 12.5523;
var x = floatNumber - Math.Truncate(floatNumber);
結果はあなたが好きなように変換することができます
var decPlaces = (int)(((decimal)number % 1) * 100);
これは、あなたの数が小数点以下2桁しかないことを前提としています。
(318.40d % 1) * 100出力39.9999999999977、丸め誤差を回避するためにキャストを使用できます:var decPlaces = (int)(((decimal)number % 1) * 100);
丸めの問題のない解決策:
double number = 10.20;
var first2DecimalPlaces = (int)(((decimal)number % 1) * 100);
Console.Write("{0:00}", first2DecimalPlaces);
出力: 20
10進数にキャストしなかった場合は、を出力することに注意してください
19。
また:
318.40出力:40(代わりに39)47.612345出力:61(代わりに612345)3.01出力:01(代わりに1)財務数値を使用している場合、たとえばこの場合、取引金額のセント部分を取得しようとしている場合は、常に
decimalデータ型を使用してください。
更新:
以下は、文字列として処理する場合にも機能します(@SearchForKnowledgeの回答に基づいて構築)。
10.2d.ToString("0.00", CultureInfo.InvariantCulture).Split('.')[1]
その後、を使用Int32.Parseしてそれをintに変換できます。
もっと良い方法 -
double value = 10.567;
int result = (int)((value - (int)value) * 100);
Console.WriteLine(result);
出力-
56
10.20それが出力します19。私の答えを見てください。
このスレッドは古くなっていると思いますが、Math.Floorについて誰も言及していないとは信じられません。
//will always be .02 cents
(10.02m - System.Math.Floor(10.02m))
double fract(double x) { return x - System.Math.Floor(x); }
int last2digits = num - (int) ((double) (num / 100) * 100);
318.401567d、ソリューションが期待される0.401567場所に出力します40。
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;
}
これは私が同様の状況のために書いた拡張メソッドです。私のアプリケーションは、2.3または3.11の形式で数値を受け取ります。ここで、数値の整数成分は年を表し、小数成分は月を表します。
// Sample Usage
int years, months;
double test1 = 2.11;
test1.Split(out years, out months);
// years = 2 and months = 11
public static class DoubleExtensions
{
public static void Split(this double number, out int years, out int months)
{
years = Convert.ToInt32(Math.Truncate(number));
double tempMonths = Math.Round(number - years, 2);
while ((tempMonths - Math.Floor(tempMonths)) > 0 && tempMonths != 0) tempMonths *= 10;
months = Convert.ToInt32(tempMonths);
}
}
ダブルを文字列に変換した後.、Remove()関数を使用して小数を取得しようとしているダブルからドットを削除して、必要な操作を実行できるようにすることができます。
_Doubleの値を2倍にすることを検討してください。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)
別の解決策
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
正規表現を使用する:Regex.Match("\.(?\d+)")ここで間違っている場合は、誰かが私を修正します
Regex.Matchがありませんが、小数の値を取得しようとすると、次のエラーが発生しましたArgumentException was unhandled: parsing "\.(?\d+)" - Unrecognized grouping construct.
使ってみませんint y = value.Split('.')[1];か?
このSplit()関数は値を個別のコンテンツに分割し、の1後に2番目の値を出力します。.
Int32.Parse((12.05123d.ToString("0.00").Split('.')[1]))