Java의 이중 십진수 형식
소수점 이하 자릿수 형식을 지정하는 데 문제가 있습니다. 예를 들어 4.0과 같은 이중 값이있는 경우 소수점을 대신 4.00으로 지정하려면 어떻게해야합니까?
방법 중 하나는 NumberFormat을 사용하는 것 입니다.
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(4.0));
산출:
4.00
Java 8에서는 format
방법 을 사용할 수 있습니다 .. :-
System.out.format("%.2f", 4.0); // OR
System.out.printf("%.2f", 4.0);
f
floating
포인트 가치 로 사용됩니다 ..2
소수점 이하는 소수점 이하 자릿수를 나타냅니다..
대부분의 Java 버전의 경우 다음을 사용할 수 있습니다 DecimalFormat
.-
DecimalFormat formatter = new DecimalFormat("#0.00");
double d = 4.0;
System.out.println(formatter.format(d));
String.format 사용 :
String.format("%.2f", 4.52135);
String.format을 사용하여 다음을 수행 할 수 있습니다.
double price = 52000;
String.format("$%,.2f", price);
@Vincent의 답변과 다른 쉼표를 확인하십시오.
산출:
$52,000.00
형식화에 대한 좋은 리소스 는 주제에 대한 공식 Java 페이지입니다.
항상 정적 메서드를 사용할 수 printf from System.out
있습니다. 그런 다음 해당 포맷터를 구현합니다. 이렇게하면 다른 예제에서 수행해야하는 힙 공간이 절약됩니다.
전의:
System.out.format("%.4f %n", 4.0);
System.out.printf("%.2f %n", 4.0);
꽤 큰 보너스 인 힙 공간을 절약합니다. 그럼에도 불구하고 저는이 예제가 다른 어떤 답변보다 훨씬 더 관리하기 쉽다고 생각합니다. 특히 대부분의 프로그래머가 C에서 printf 함수를 알고 있기 때문에 (Java는 함수 / 메소드를 약간 변경합니다).
new DecimalFormat("#0.00").format(4.0d);
double d = 4.0;
DecimalFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
System.out.println(nf.format("#.##"));
다른 방법은 클래스 의 setMinimumFractionDigits
방법을 사용하는 것입니다 NumberFormat
.
여기서 기본적으로 소수점 뒤에 표시 할 숫자 수를 지정합니다.
따라서 입력은 지정된 금액이 2라고 가정하여 4.0
생성 4.00
됩니다.
그러나 Double
입력에 지정된 양보다 많은 양이 포함 된 경우 지정된 최소 금액을 취한 다음 반올림 / 내림하여 한 자리를 더 추가합니다.
예를 들어 4.15465454
최소 2 개를 지정하면4.155
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
Double myVal = 4.15465454;
System.out.println(nf.format(myVal));
아래 방법 중 하나를 사용할 수 있습니다.
사용하는 경우
java.text.DecimalFormat
DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance(); decimalFormat.setMinimumFractionDigits(2); System.out.println(decimalFormat.format(4.0));
또는
DecimalFormat decimalFormat = new DecimalFormat("#0.00"); System.out.println(decimalFormat.format(4.0));
간단한 문자열 형식으로 변환하려는 경우
System.out.println(String.format("%.2f", 4.0));
위의 모든 코드는 4.00 을 인쇄합니다.
100 % 작동합니다.
import java.text.DecimalFormat;
public class Formatting {
public static void main(String[] args) {
double value = 22.2323242434342;
// or value = Math.round(value*100) / 100.0;
System.out.println("this is before formatting: "+value);
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
}
}
이 작업을 수행 할 수있는 방법은 많습니다. 다음은 다음과 같습니다.
원래 번호가 다음과 같이 주어 졌다고 가정합니다.
double number = 2354548.235;
NumberFormat 사용 :
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(number));
String.format 사용 :
System.out.println(String.format("%,.2f", number));
DecimalFormat 및 패턴 사용 :
NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
DecimalFormat decimalFormatter = (DecimalFormat) nf;
decimalFormatter.applyPattern("#,###,###.##");
String fString = decimalFormatter.format(number);
System.out.println(fString);
DecimalFormat 및 패턴 사용
DecimalFormat decimalFormat = new DecimalFormat("############.##");
BigDecimal formattedOutput = new BigDecimal(decimalFormat.format(number));
System.out.println(formattedOutput);
모든 경우에 출력 은 2354548.23입니다.
참고 :
During rounding you can add RoundingMode
in your formatter. Here are some rounding mode given bellow:
decimalFormat.setRoundingMode(RoundingMode.CEILING);
decimalFormat.setRoundingMode(RoundingMode.FLOOR);
decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
decimalFormat.setRoundingMode(RoundingMode.UP);
Here are the imports:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
First import NumberFormat
. Then add this:
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
This will give you two decimal places and put a dollar sign if it's dealing with currency.
import java.text.NumberFormat;
public class Payroll
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
int hoursWorked = 80;
double hourlyPay = 15.52;
double grossPay = hoursWorked * hourlyPay;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));
}
}
You can do it as follows:
double d = 4.0;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
I know that this is an old topic, but If you really like to have the period instead of the comma, just save your result as X,00 into a String and then just simply change it for a period so you get the X.00
The simplest way is just to use replace.
String var = "X,00";
String newVar = var.replace(",",".");
The output will be the X.00 you wanted. Also to make it easy you can do it all at one and save it into a double variable:
Double var = Double.parseDouble(("X,00").replace(",",".");
I know that this reply is not useful right now but maybe someone that checks this forum will be looking for a quick solution like this.
참고URL : https://stackoverflow.com/questions/12806278/double-decimal-formatting-in-java
'developer tip' 카테고리의 다른 글
1 열 테이블이 좋은 디자인입니까? (0) | 2020.08.14 |
---|---|
입력 필드에 텍스트 추가 (0) | 2020.08.14 |
WPF 앱을 화면 중앙에 배치하는 방법은 무엇입니까? (0) | 2020.08.14 |
서버 응답 헤더 IIS7 제거 (0) | 2020.08.14 |
OpenCV에서 Mat :: type ()을 사용하여 Mat 객체의 유형을 찾는 방법 (0) | 2020.08.14 |