programing

소수점 이하 2자리까지 반올림 할 수 있나요?

goodcopy 2022. 10. 7. 21:36
반응형

소수점 이하 2자리까지 반올림 할 수 있나요?

stackoverflow 질문을 많이 읽었는데 하나도 효과가 없는 것 같습니다.math.round()반올림하다코드는 다음과 같습니다.

class round{
    public static void main(String args[]){

    double a = 123.13698;
    double roundOff = Math.round(a*100)/100;

    System.out.println(roundOff);
}
}

출력은 다음과 같습니다.123하지만 나는 그것이 되길 바란다.123.14. 그 추가 내용을 읽었습니다.*100/100도움이 되겠지만, 보다시피, 난 그걸 제대로 작동시키지 못했어.

입력과 출력 모두 더블이 되는 것은 매우 중요합니다.

위의 코드 4행을 변경하여 게시해주시면 감사하겠습니다.

음, 이건...

double roundOff = Math.round(a * 100.0) / 100.0;

출력은

123.14

또는 @Rufein의 말대로

 double roundOff = (double) Math.round(a * 100) / 100;

이것도 너에게 도움이 될 거야.

     double d = 2.34568;
     DecimalFormat f = new DecimalFormat("##.00");
     System.out.println(f.format(d));
String roundOffTo2DecPlaces(float val)
{
    return String.format("%.2f", val);
}
BigDecimal a = new BigDecimal("123.13698");
BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(roundOff);

코드로 돌아가서100타고100.00효과가 있는지 알려주세요.단, 격식을 차리고 싶다면 다음을 시도해 보십시오.

import java.text.DecimalFormat;
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;
double roundOff = Math.round(a*100)/100;

그래야 한다

double roundOff = Math.round(a*100)/100D;

100에 'D'를 더하면 이중 리터럴이 되므로 생성된 결과는 정밀도를 가질 수 있습니다.

나는 이것이 2년 된 질문이라는 것을 알지만 모든 사람이 어느 시점에 가치를 반올림하는 문제에 직면하기 때문에.다른 방법을 공유하고자 합니다. 어떤 척도로든 반올림된 값을 얻을 수 있습니다.BigDecimal학급.이 경우 최종 값을 얻기 위해 필요한 추가 단계를 피할 수 있습니다.DecimalFormat("0.00")또는 사용Math.round(a * 100) / 100.

import java.math.BigDecimal;

public class RoundingNumbers {
    public static void main(String args[]){
        double number = 123.13698;
        int decimalsToConsider = 2;
        BigDecimal bigDecimal = new BigDecimal(number);
        BigDecimal roundedWithScale = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("Rounded value with setting scale = "+roundedWithScale);

        bigDecimal = new BigDecimal(number);
        BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
        System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);

    }
}

이 프로그램은 다음과 같은 출력을 제공합니다.

Rounded value with setting scale = 123.14
Rounded value with Dividing by one = 123.14

시도:

class round{
public static void main(String args[]){

double a = 123.13698;
double roundOff = Math.round(a*100)/100;
String.format("%.3f", roundOff); //%.3f defines decimal precision you want
System.out.println(roundOff);   }}

이 방법은 길지만 완전히 검증된 솔루션이며, 실패하는 일은 없습니다.

이 함수에 숫자를 2배로 전달하기만 하면 소수점 값을 가장 가까운 값인 5로 반올림할 수 있습니다.

4.25의 경우 출력 4.25

4.20의 경우 출력 4.20

4.24의 경우 출력 4.20

4.26의 경우 출력 4.30

소수점 이하 2자리까지 반올림하려면

DecimalFormat df = new DecimalFormat("#.##");
roundToMultipleOfFive(Double.valueOf(df.format(number)));

최대 3자리일 경우 새로운 DecimalFormat("#")을 입력합니다.###")

최대 n자리일 경우 새로운 DecimalFormat("#")을 입력합니다.n회수)

 public double roundToMultipleOfFive(double x)
            {

                x=input.nextDouble();
                String str=String.valueOf(x);
                int pos=0;
                for(int i=0;i<str.length();i++)
                {
                    if(str.charAt(i)=='.')
                    {
                        pos=i;
                        break;
                    }
                }

                int after=Integer.parseInt(str.substring(pos+1,str.length()));
                int Q=after/5;
                int R =after%5;

                if((Q%2)==0)
                {
                    after=after-R;
                }
                else
                {
                   if(5-R==5)
                   {
                     after=after;
                   }
                   else after=after+(5-R);
                }

                       return Double.parseDouble(str.substring(0,pos+1).concat(String.valueOf(after))));

            }

정수 산술에 걸린 것 같습니다.일부 언어에서는 (int)/(int)는 항상 정수 산술로 평가됩니다.부동소수점 연산을 강제하려면 적어도1개의 피연산자가 비연산인지 확인합니다.

double roundOff = Math.round(a*100)/100.f;

방금 코드를 수정했습니다.내 시스템에서는 정상적으로 동작한다.도움이 되는지 확인

class round{
    public static void main(String args[]){

    double a = 123.13698;
    double roundOff = Math.round(a*100)/100.00;

    System.out.println(roundOff);
}
}
public static float roundFloat(float in) {
    return ((int)((in*100f)+0.5f))/100f;
}

대부분의 경우엔 괜찮을 겁니다.예를 들어 double을 준수하려면 유형을 변경할 수 있습니다.

언급URL : https://stackoverflow.com/questions/11701399/round-up-to-2-decimal-places-in-java

반응형