소수점 이하의 숫자를 정수 형태로 받고 싶습니다. 예를 들어, 1.05에서 05 만 또는 0.50이 아닌 2.50에서 50 만
decimal, float, string, ...?
소수점 이하의 숫자를 정수 형태로 받고 싶습니다. 예를 들어, 1.05에서 05 만 또는 0.50이 아닌 2.50에서 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"
Regex에 대한 자세한 내용은 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);
이것은 당신의 숫자가 소수점 두 자리 만 가지고 있다고 가정합니다.
(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
십진수로 캐스트하지 않으면
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로 변환 할 수 있습니다 .
이 스레드가 늙어 가고 있다고 생각하지만 아무도 Math를 언급하지 않았다는 것을 믿을 수 없습니다.
//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);
}
}
double을 문자열로 변환 한 후 함수 .를 사용하여 소수점을 얻으려는 double 에서 점 을 제거하여 Remove()필요한 작업을 수행 할 수 있습니다.
이중 가지고 고려 _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)
또 다른 해결책
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.
매우 간단합니다
float moveWater = Mathf.PingPong(theTime * speed, 100) * .015f;
int m = (int)(moveWater);
float decimalPart= moveWater -m ;
Debug.Log(decimalPart);