Files
gwcf-review-front/src/lib/utils.ts

63 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import {VIEW_DECIMAL_POINT} from "@/const/common.const";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export const formatKoreanBaseDate = (date = new Date()) => {
const year = String(date.getFullYear()).slice(-2);
return `${year}년 ${date.getMonth() + 1}월 ${date.getDate()}일 기준`;
};
/**
* 다양한 형식의 값을 숫자로 파싱합니다.
* - 쉼표, 퍼센트, 유니코드 마이너스 자동 처리
* - null/undefined/빈문자열/"−" 등은 null 반환
* - 유한하지 않은 숫자는 null 반환
*/
export function parseNumber(
value: unknown,
options?: {
allowComma?: boolean; // 기본값: true
allowPercent?: boolean; // 기본값: true
allowMinus?: boolean; // 기본값: true (유니코드 마이너스 포함)
}
): number | null {
const { allowComma = true, allowPercent = true, allowMinus = true } = options ?? {};
if (value === null || value === undefined) return null;
if (typeof value === "number") {
return Number.isFinite(value) ? value : null;
}
if (typeof value === "string") {
let s = value.trim();
if (s === "" || s === "-" || s === "−") return null;
s = s.replaceAll("(", "");
s = s.replaceAll(")", "");
if (allowComma) s = s.replaceAll(",", "");
if (allowPercent) s = s.replaceAll("%", "");
if (allowMinus) s = s.replaceAll("−", "-"); // 유니코드 마이너스 -> ASCII 마이너스
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
return null;
}
export const roundNumber = (num: number|null, decimalPoint?: number) => {
if(num == null) return null;
decimalPoint ??= VIEW_DECIMAL_POINT;
const factor = 10 ** decimalPoint;
return Math.round(num * factor) / factor;
};