Skip to content

Instantly share code, notes, and snippets.

@trinhvanminh
Created July 5, 2023 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trinhvanminh/416d2a5c61d8eadad800c7fa5587f045 to your computer and use it in GitHub Desktop.
Save trinhvanminh/416d2a5c61d8eadad800c7fa5587f045 to your computer and use it in GitHub Desktop.
Vietnamese number formatter
import dayjs from "dayjs";
import { round, isNil } from "lib/utils"; // from lodash
import numeral from "numeral";
numeral.register("locale", "vi", {
delimiters: {
thousands: ".",
decimal: ",",
},
abbreviations: {
thousand: "k",
million: "tr",
billion: "tỷ",
trillion: "nghìn tỷ",
},
ordinal(number) {
return number;
},
currency: {
symbol: "đ",
},
});
numeral.locale("vi");
const formatter = {
toCurrency(value, digits = 2) {
return !isNil(value)
? numeral(value).format(`0,.[${"0".repeat(digits)}] $`)
: null;
},
toRoundingNumber(value, step = 500) {
if (isNil(value)) {
return null;
}
if (step > 1 && value > 0) {
const precision =
value % step ? -step.toString().length : -(step.toString().length - 1);
return round(value, precision);
} else return 0;
},
toDate(value) {
return !isNil(value) ? dayjs(value).format("L") : null;
},
toDateWithoutYear(value) {
return !isNil(value) ? dayjs(value).format("DD/MM") : null;
},
toTime(value) {
return !isNil(value) ? dayjs(value).format("LT") : null;
},
toDateTime(value) {
return !isNil(value) ? dayjs(value).format("LLL") : null;
},
toShortDateTime(value) {
return !isNil(value) ? dayjs(value).format("L LT") : null;
},
toNumeric(value) {
return !isNil(value) ? numeral(value).format("0,0[.]00") : null;
},
toAcronymCurrency(value) {
return !isNil(value) ? numeral(value).format("0.0a") : null;
},
toPercentage(value) {
return !isNil(value) ? numeral(value).format("0,.[00]%") : null;
},
};
export default formatter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment