자바에서 소수점 이하 2 자리까지 반올림? [복제]
이 질문에는 이미 답변이 있습니다.
- Java 30 답변 에서 소수점 이하 자릿수를 반올림하는 방법
나는 많은 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); }}
이것은 길지만 완전한 증거 솔루션이며 결코 실패하지 않습니다.
이 함수에 숫자를 두 배로 전달하면 소수점 이하 자릿수를 가장 가까운 5로 반올림합니다.
4.25 인 경우 출력 4.25
if 4.20, Output 4.20
if 4.24, Output 4.20
if 4.26, Output 4.30
if you want to round upto 2 decimal places,then use
DecimalFormat df = new DecimalFormat("#.##");
roundToMultipleOfFive(Double.valueOf(df.format(number)));
if up to 3 places, new DecimalFormat("#.###")
if up to n places, new DecimalFormat("#.nTimes #")
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))));
}
seems like you are hit by integer arithmetic: in some languages (int)/(int) will always be evaluated as integer arithmetic. in order to force floating-point arithmetic, make sure that at least one of the operands is non-integer:
double roundOff = Math.round(a*100)/100.f;
I just modified your code. It works fine in my system. See if this helps
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;
}
Should be ok for most cases. You can still changes types if you want to be compliant with doubles for instance.
참고URL : https://stackoverflow.com/questions/11701399/round-up-to-2-decimal-places-in-java
'Programming' 카테고리의 다른 글
Docker에서 디렉토리 변경 명령? (0) | 2020.05.21 |
---|---|
한 요소가 다른 요소에 포함되어 있는지 Javascript를 확인하는 방법 (0) | 2020.05.21 |
테이블의 기본 데이터 정렬을 변경하는 방법은 무엇입니까? (0) | 2020.05.21 |
styles.xml에서 'Theme'기호를 확인할 수 없습니다 (Android Studio) (0) | 2020.05.21 |
활동하지 않는 장소에서 getLayoutInflater ()를 호출 (0) | 2020.05.21 |