Frontend/Flutter

[Flutter] intl 라이브러리 NumberFormat 사용법(숫자 세자리마다 콤마, 소수점 두자리, 만 단위 표시)

김룹 2024. 2. 5. 20:51

 

intl install | Dart package

Contains code to deal with internationalized/localized messages, date and number formatting and parsing, bi-directional text, and other internationalization issues.

pub.dev

 

먼저 intl 라이브러리를 추가한다.

flutter pub add intl

또는

dart pub add intl

 

dependencies:
  intl: ^0.19.0
  
  
 import 'package:intl/intl.dart';

 

 

 

ICU 패턴 

0 한 자릿수
# 값이 0이면 생략되는 한 자리 숫자
. 소수점 구분 기호
- 빼기 기호
, 그룹화 구분
E 가수와 지수를 구분
+- 지수 앞에 더하기 기호 붙여야 함
%- 접두사 또는 접미사에서 100을 곱하여 백분율로 표시
(\u2030) 접두사 또는 접미사에서 1000을 곱하고 밀리 단위로 표시
¤ (\u00A4) 통화 기호, 통화 이름으로 대체
' 특수 문자를 인용할 때 사용
; positive 패턴과 negative 패턴을 구분하는 데 사용(둘 다 있는 경우)

 

 

 

소수점 두자리까지 출력 

var f = NumberFormat('###.0#', 'en_US');
print(f.format(12.345));
//  ==> 12.34

 

 

숫자 세자리마다 콤마 넣기 

var f = NumberFormat('###,###,###,###');
print(f.format(1000000);
// ==> 1,000,000

 

 

또는 아래와 같이 쉽게 NumberFormat.currency 사용하는 방법 있음!

var f = NumberFormat.currency(locale: "ko_KR", symbol: "");
print(f.format(553000));
// ==> 553,000

 

 

만약 화폐 단위를 함께 표시하고 싶다면, 아래와 같이 symbol에 작성해주면 됨.

만약 symbol을 별도로 작성하지 않는다면, default로 KRW 이 붙는다

var f = NumberFormat.currency(locale: "ko_KR", symbol: "₩");
print(f.format(553000));
// ==> ₩553,000


var f = NumberFormat.currency(locale: "ko_KR");
print(f.format(553000));
// ==> KRW553,000

 

 

만 단위로 표시하는 방법 

int price = 157000;
double temp = param / 10000;
var f = NumberFormat("###,###,###.#### 만원");
print(f.format(temp);
// ==> 15.7 만원

 

 

 

 

🌐 공식문서 링크

https://pub.dev/documentation/intl/latest/intl/NumberFormat/NumberFormat.currency.html