문자열 번호에 쉼표와 반올림 형식을 지정하려면 어떻게 해야 합니까?
문자열로 지정된 다음 번호의 형식을 지정하는 가장 좋은 방법은 무엇입니까?
String number = "1000500000.574" //assume my value will always be a String
다음 값을 가진 문자열로 지정합니다.1,000,500,000.57
어떻게 포맷하면 좋을까요?
클래스는 다양한 로케일을 지원하므로 참조할 수 있습니다(예를 들어 다음과 같이 포맷되는 국가에서는:1.000.500.000,57대신).
또한 이 문자열을 숫자로 변환해야 합니다.이 작업은 다음 방법으로 수행할 수 있습니다.
double amount = Double.parseDouble(number);
코드 샘플:
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
이것은 String을 사용하여 실행할 수도 있습니다.format(형식)을 지정합니다.이것은, 1 개의 문자열에 복수의 번호를 포맷 하는 경우, 보다 간단하게 또는 보다 유연하게 할 수 있습니다.
String number = "1000500000.574";
Double numParsed = Double.parseDouble(number);
System.out.println(String.format("The input number is: %,.2f", numParsed));
// Or
String numString = String.format("%,.2f", numParsed);
형식 문자열 "%.2f" - "에서 은 쉼표가 있는 개별 숫자 그룹을 의미하며, ".2"는 소수점 뒤의 두 자리까지 반올림을 의미합니다.
그 외의 포맷 옵션에 대해서는, https://docs.oracle.com/javase/tutorial/java/data/numberformat.html 를 참조해 주세요.
String을 숫자로 변환하면
// format the number for the default locale
NumberFormat.getInstance().format(num)
또는
// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
이것이 구글의 가장 중요한 결과입니다.format number commas java소수점 따위는 신경 쓰지 않고 정수만 쓰는 사람들에게 효과가 있는 답이 있다.
String.format("%,d", 2000000)
출력:
2,000,000
나만의 포맷 유틸리티를 만들었습니다.포맷 처리 속도가 매우 빠르고 다양한 기능을 제공합니다.
지원 대상:
- 쉼표 포맷 예: 1234567은 1,234,567이 됩니다.
- 앞에 "Thousand(K)", "Million(M)", "Billion(B)", "Tillion(T)"가 붙습니다.
- 정밀도는 0 ~ 15 입니다.
- 정밀도 크기 조정(정밀도를 6자리 사용하지만 사용 가능한 자릿수가 3자리인 경우 강제로 3자리)
- Prefix downing(선택한 Prefix가 너무 클 경우 보다 적절한 Prefix로 낮아지는 것을 의미합니다).
코드는 여기서 찾을 수 있습니다.이렇게 부르죠.
public static void main(String[])
{
int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
String formatted = ValueFormat.format(1234567, settings);
}
또한 소수점 지원은 처리하지 않지만 정수 값에는 매우 유용합니다.위의 예에서는 출력으로 "1.23M"이 표시됩니다.십진수 지원을 추가할 수도 있지만, 그 이후로는 수학 계산을 위해 압축된 char[] 배열을 처리하는 BigInteger 유형의 클래스에 병합하는 것이 더 나을 것 같습니다.
public void convert(int s)
{
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}
public static void main(String args[])
{
LocalEx n=new LocalEx();
n.convert(10000);
}
아래의 솔루션도 사용할 수 있습니다.
public static String getRoundOffValue(double value){
DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
return df.format(value);
}
다음 코드를 사용하여 전체 변환을 한 줄로 수행할 수 있습니다.
String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));
DecimalFormat 생성자의 마지막 두 개의 # 기호도 0s일 수 있습니다.어느 쪽이든 좋다.
첫 번째 답변은 매우 잘 작동하지만 ZERO / 0의 경우 .00으로 포맷됩니다.
그래서 #,##0.00 포맷이 잘 작동하고 있습니다.프로덕션 시스템에 배포하기 전에 항상 0 / 100 / 2334.30 및 음수 등 다른 수치를 테스트하십시오.
가장 간단한 방법은 다음과 같습니다.
String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result));
출력: 10,987,655.88
언급URL : https://stackoverflow.com/questions/3672731/how-can-i-format-a-string-number-to-have-commas-and-round
'source' 카테고리의 다른 글
| Linux 커널은 어떻게 컴파일 할 수 있습니까? (0) | 2022.08.11 |
|---|---|
| Collections.emptyMap()과 새로운 HashMap()의 비교 (0) | 2022.08.11 |
| Deque over Stack을 사용해야 하는 이유 (0) | 2022.08.11 |
| Java 순서 맵 (0) | 2022.08.11 |
| Java의 SimpleDateFormat이 스레드 세이프가 아닌 이유는 무엇입니까? (0) | 2022.08.11 |