값 C #을 가장 가까운 정수로 반올림하는 방법은 무엇입니까?


79

double을 int로 반올림하고 싶습니다.

예 :

double a=0.4, b=0.5;

둘 다 정수로 변경하고 싶습니다.

그래서

int aa=0, bb=1;

aa은 (는)에서 a이며 bb에서 왔습니다 b.

그렇게 할 공식이 있습니까?


5
double이 int 범위를 벗어나면 어떻게 하시겠습니까?
Eric Lippert

답변:


208

사용 Math.Ceiling라운드 최대

Math.Ceiling(0.5); // 1

사용 Math.Round다만 라운드

Math.Round(0.5, MidpointRounding.AwayFromZero); // 1

그리고 Math.Floor내림

Math.Floor(0.5); // 0

Math.Round로 더 많은 작업을해야합니다. 동작을 정확하게 지정하기 위해 열거 형 (MidpointRounding)을 제공합니다.
jnielsen

@jnielsen : 그것을 지적하고 코드 예제를 주셔서 감사합니다. 나는 그것을 고쳤다.
BrunoLM 2010 년

가장 간단하고 효과적인 방법은 Math.Ceiling
yopez83

그주의 Math.Ceiling는 것, 숫자가 이미 전체의 경우 같은 번호를 반환하지 라운드까지 1 일까지
큰 돈


6

.NET 프레임 워크는 Math.Round기본적으로 은행원의 반올림을 사용합니다 . 이 오버로드를 사용해야합니다.

Math.Round(0.5d, MidpointRounding.AwayFromZero)  //1
Math.Round(0.4d, MidpointRounding.AwayFromZero)  //0

3

대신 함수를 사용하십시오 MidpointRounding.AwayFromZero.

myRound(1.11125,4)

답변 :-1.1114

public static Double myRound(Double Value, int places = 1000)
{
    Double myvalue = (Double)Value;
    if (places == 1000)
    {
        if (myvalue - (int)myvalue == 0.5)
        {
            myvalue = myvalue + 0.1;
            return (Double)Math.Round(myvalue);
        }
        return (Double)Math.Round(myvalue);
        places = myvalue.ToString().Substring(myvalue.ToString().IndexOf(".") + 1).Length - 1;
    } if ((myvalue * Math.Pow(10, places)) - (int)(myvalue * Math.Pow(10, places)) > 0.49)
    {
        myvalue = (myvalue * Math.Pow(10, places + 1)) + 1;
        myvalue = (myvalue / Math.Pow(10, places + 1));
    }
    return (Double)Math.Round(myvalue, places);
}

2
현재 문화권이 소수점에 마침표 대신 쉼표를 사용하면 실패합니다.
Sean Reid

3

수학 라운드

배정 밀도 부동 소수점 값을 가장 가까운 정수 값으로 반올림합니다.


그러나 : "이 방법의 동작은 IEEE 표준 754, 섹션 4를 따릅니다. 이러한 종류의 반올림을 가장 가까운 반올림 또는 은행가 반올림이라고도합니다. ..."

0

Math.Round (0.5)는 부동 소수점 반올림 오류로 인해 0을 반환하므로 반올림하지 않도록 원래 값에 반올림 오류 양을 추가해야합니다.

Console.WriteLine(Math.Round(0.5, 0).ToString()); // outputs 0 (!!)
Console.WriteLine(Math.Round(1.5, 0).ToString()); // outputs 2
Console.WriteLine(Math.Round(0.5 + 0.00000001, 0).ToString()); // outputs 1
Console.WriteLine(Math.Round(1.5 + 0.00000001, 0).ToString()); // outputs 2
Console.ReadKey();

나 한테는 상관 없어 .. 나도 알아 냈어.
윌리엄

8
오류가 없습니다. 1/2은 정확히 double로 표현할 수 있습니다. 문서에서는 "a의 분수 구성 요소가 두 정수 중 하나가 짝수이고 다른 하나가 홀수 인 경우, 짝수를 반환합니다."라고 말합니다. 0은 짝수입니다. 이 퍼지 요소는 0.499999995와 같은 숫자를 잘못 반올림합니다.
Matthew Flaschen

헤즈 업 건배. 나는 OP가 Round가 다른 사람들이 제안한 것처럼 간단하게 작동하지 않는다는 것을 알도록 노력했습니다. 고맙게도 OP는 이제 그것을 조심하는 것을 알고 있으며 Round에 대해 더 잘 이해하고 있습니다. =)

0

음의 정수를 반올림 할 수도 있습니다.

// performing d = c * 3/4 where d can be pos or neg
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
// explanation:
// 1.) multiply:          c * a  
// 2.) if c is negative:  (c>0? subtract half of the dividend 
//                              (b>>1) is bit shift right = (b/2)
//     if c is positive:  else  add half of the dividend 
// 3.) do the division
// on a C51/52 (8bit embedded) or similar like ATmega the below code may execute in approx 12cpu cycles (not tested)

여기 어딘가의 팁에서 확장되었습니다. 죄송합니다. 어디에서 놓쳤습니다.

/* Example test: integer rounding example including negative*/
#include <stdio.h>
#include <string.h>

int main () {
   //rounding negative int
   // doing something like d = c * 3/4
   int a=3;
   int b=4;
   int c=-5;
   int d;
   int s=c;
   int e=c+10;


   for(int f=s; f<=e; f++) {
      printf("%d\t",f);

      double cd=f, ad=a, bd=b , dd;

      // d = c * 3/4  with double
      dd = cd * ad / bd;

      printf("%.2f\t",dd);
      printf("%.1f\t",dd);        
      printf("%.0f\t",dd);

      // try again with typecast have used that a lot in Borland C++ 35 years ago....... maybe evolution has overtaken it ;) ***
      // doing div before mul on purpose
      dd =(double)c * ((double)a / (double)b);
      printf("%.2f\t",dd);

      c=f;
      // d = c * 3/4  with integer rounding
      d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
      printf("%d\t",d);
      puts("");
  }
 return 0;
}

/* test output
in  2f     1f   0f cast int   
-5  -3.75   -3.8    -4  -3.75   -4  
-4  -3.00   -3.0    -3  -3.75   -3  
-3  -2.25   -2.2    -2  -3.00   -2  
-2  -1.50   -1.5    -2  -2.25   -2  
-1  -0.75   -0.8    -1  -1.50   -1  
 0   0.00    0.0     0  -0.75    0  
 1   0.75    0.8     1   0.00    1  
 2   1.50    1.5     2   0.75    2  
 3   2.25    2.2     2   1.50    2  
 4   3.00    3.0     3   2.25  3    
 5   3.75    3.8     4   3.00   

// by the way evolution: 
// Is there any decent small integer library out there for that by now?

-2

간단하다. 따라서이 코드를 따르십시오.

decimal d = 10.5;
int roundNumber = (int)Math.Floor(d + 0.5);

결과는 11입니다.


Math.FloorOP가 가장 가까운 반올림을 원할 때 왜 사용 합니까? 음수 값에는 작동하지 않습니다
phuclv

이 예는 양수 값에만 해당됩니다.
TechnicalKalsa

당신은 당신의 질문에서 그것을 언급하지 않았습니다. 그리고 OP는 그가 양의 정수에만 관심이 있다고 말하지 않았습니다. 어쨌든 이것은 이미 Math.Round가 있기 때문에 쓸모가 없습니다
phuclv

-2

다른 옵션 :

string strVal = "32.11"; // will return 33
// string strVal = "32.00" // returns 32
// string strVal = "32.98" // returns 33

string[] valStr = strVal.Split('.');

int32 leftSide = Convert.ToInt32(valStr[0]);
int32 rightSide = Convert.ToInt32(valStr[1]);

if (rightSide > 0)
    leftSide = leftSide + 1;


return (leftSide);
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.