Java에서 소수점 이하 두 자리로 반올림하는 방법은 무엇입니까?
이 질문에 이미 답변이 있습니다.
이것은 소수점 이하 2 자리에서 두 배를 반올림하기 위해 한 것입니다.
amount = roundTwoDecimals(amount);
public double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
금액 = 25.3569 또는 그와 비슷한 경우 훌륭하게 작동하지만 금액 = 25.00 또는 금액 = 25.0이면 25.0을 얻습니다! 내가 원하는 것은 소수점 이하 두 자리로 반올림하고 서식을 지정하는 것입니다.
돈으로 일하고 있습니까? 을 생성 한 String
다음 다시 변환하는 것은 꽤 반복적입니다.
사용 BigDecimal
. 이것은 꽤 광범위하게 논의되었습니다. 당신은해야 Money
클래스를하고 양이이어야한다 BigDecimal
.
돈으로 일하지 않더라도 BigDecimal
.
그냥 사용 : (파이처럼 쉬움)
double number = 651.5176515121351;
number = Math.round(number * 100);
number = number/100;
출력은 651.52입니다.
숫자 자리 표시 자 ( 0
)를 사용합니다. ' #
'후행 / 선행 0이없는 것으로 표시됩니다.
DecimalFormat twoDForm = new DecimalFormat("#.00");
당신은 할 수 없습니다 복식 소수점 장소가 없기 때문에, '더블 라운드 소수점 이하 자릿수 [임의의 수]에'. 10 진수에는 소수 자리가 있기 때문에 double을 10 진수로 된 10 진수 문자열로 변환 할 수 있습니다. 왜냐하면 10 진수에는 소수 자리가 있기 때문입니다. 그러나 다시 변환하면 2 진수 소수 자릿수를 사용하는 이중 랜드로 돌아갑니다 .
이것을 사용하십시오
String.format ( "%. 2f", doubleValue) // 요구 사항에 따라 2를 변경합니다.
이것은 내가 할 수있는 가장 간단한 방법이지만 본 대부분의 예보다 훨씬 쉽게 작업을 수행 할 수 있습니다.
double total = 1.4563;
total = Math.round(total * 100);
System.out.println(total / 100);
결과는 1.46입니다.
Apache common에서 org.apache.commons.math.util.MathUtils를 사용할 수 있습니다.
double round = MathUtils.round(double1, 2, BigDecimal.ROUND_HALF_DOWN);
Apache Commons Math를 사용할 수 있습니다.
Precision.round(double x, int scale)
Money 클래스는 Long의 하위 클래스로 표시되거나 money 값을 네이티브 long으로 나타내는 멤버를 가질 수 있습니다. 그런 다음 돈 인스턴스화에 값을 할당 할 때 항상 실제로 실제 돈 값인 값을 저장하게됩니다. Money 객체를 (Money의 재정의 된 toString () 메서드를 통해) 적절한 형식으로 출력하기 만하면됩니다. 예를 들어 Money 객체의 내부 표현에서 $ 1.25는 125입니다. 돈을 센트 나 펜스 또는 봉인하는 통화의 최소 단위로 표현한 다음 출력시 형식을 지정합니다. 예를 들어 $ 1.257과 같은 '불법'화폐 가치는 절대로 저장할 수 없습니다.
두 배 금액 = 25.00;
NumberFormat 포맷터 = new DecimalFormat ( "# 0.00");
System.out.println (formatter.format (amount));
이것을 시도해 볼 수 있습니다.
public static String getRoundedValue(Double value, String format) {
DecimalFormat df;
if(format == null)
df = new DecimalFormat("#.00");
else
df = new DecimalFormat(format);
return df.format(value);
}
또는
public static double roundDoubleValue(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);
결과를 소수점 두 자리까지 표시하려면 다음을 수행하십시오.
// assuming you want to round to Infinity.
double tip = (long) (amount * percent + 0.5) / 100.0;
이 결과는 정확하지 않지만 Double.toString (double)이이를 수정하고 소수점 이하 1 ~ 2 자리를 인쇄합니다. 그러나 다른 계산을 수행하자마자 암시 적으로 반올림되지 않는 결과를 얻을 수 있습니다. ;)
Math.round
하나의 대답입니다.
public class Util {
public static Double formatDouble(Double valueToFormat) {
long rounded = Math.round(valueToFormat*100);
return rounded/100.0;
}
}
Spock, Groovy에서 테스트
void "test double format"(){
given:
Double performance = 0.6666666666666666
when:
Double formattedPerformance = Util.formatDouble(performance)
println "######################## formatted ######################### => ${formattedPerformance}"
then:
0.67 == formattedPerformance
}
금액이 양수일 수도 있고 음수 일 수도 있다고 가정하고 소수점 이하 두 자리로 반올림하면 다음 코드 스 니펫을 사용할 수 있습니다.
amount = roundTwoDecimals(amount);
public double roundTwoDecimals(double d) {
if (d < 0)
d -= 0.005;
else if (d > 0)
d += 0.005;
return (double)((long)(d * 100.0))/100);
}
Java 1.8을 시작하면 람다 식으로 더 많은 작업을 수행하고 null을 확인할 수 있습니다. 또한 다음 중 하나는 Float 또는 Double 및 가변 소수점 수 (2 :-포함)를 처리 할 수 있습니다.
public static Double round(Number src, int decimalPlaces) {
return Optional.ofNullable(src)
.map(Number::doubleValue)
.map(BigDecimal::new)
.map(dbl -> dbl.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP))
.map(BigDecimal::doubleValue)
.orElse(null);
}
여기서 num은 이중 숫자입니다.
- Integer 2 denotes the number of decimal places that we want to print.
Here we are taking 2 decimal palces
System.out.printf("%.2f",num);
Here is an easy way that guarantee to output the myFixedNumber rounded to two decimal places:
import java.text.DecimalFormat;
public class TwoDecimalPlaces {
static double myFixedNumber = 98765.4321;
public static void main(String[] args) {
System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
}
}
The result is: 98765.43
int i = 180;
int j = 1;
double div= ((double)(j*100)/i);
DecimalFormat df = new DecimalFormat("#.00"); // simple way to format till any deciaml points
System.out.println(div);
System.out.println(df.format(div));
First declare a object of DecimalFormat
class. Note the argument inside the DecimalFormat
is #.00
which means exactly 2 decimal places of rounding off.
private static DecimalFormat df2 = new DecimalFormat("#.00");
Now, apply the format to your double value:
double input = 32.123456;
System.out.println("double : " + df2.format(input)); // Output: 32.12
Note in case of double input = 32.1;
Then the output would be 32.10
and so on.
You can use this function.
import org.apache.commons.lang.StringUtils;
public static double roundToDecimals(double number, int c)
{
String rightPad = StringUtils.rightPad("1", c+1, "0");
int decimalPoint = Integer.parseInt(rightPad);
number = Math.round(number * decimalPoint);
return number/decimalPoint;
}
참고URL : https://stackoverflow.com/questions/5710394/how-do-i-round-a-double-to-two-decimal-places-in-java
'Program Tip' 카테고리의 다른 글
Scala에서 구문 설탕의 모든 인스턴스는 무엇입니까? (0) | 2020.11.27 |
---|---|
이 사용자가 익명인지 또는 실제로 내 시스템의 사용자인지 어떻게 확인합니까? (0) | 2020.11.27 |
목록 항목을 열로 표시하는 방법은 무엇입니까? (0) | 2020.11.27 |
Python의 numpy ndarray에서 비 NaN 요소 수 계산 (0) | 2020.11.27 |
값을 대문자 또는 소문자로 변경하는 SQL (0) | 2020.11.27 |