React
[React] 정상가, 할인된 금액이 있을 경우 %퍼센트 구하기
07a
2023. 7. 28. 12:12
아래와 같이 따로 ts파일을 만들어서 %를 구하는 함수를 구현했다.
regularPrice: 정상가
discountedPrice: 할인된 가격
percent를 구한후 Math.floor를 통해 소수점자리는 제외한다.
export default function calculatePercent(
regularPrice: number,
discountedPrice: number
) {
const discount = regularPrice - discountedPrice; //정상가에서 할인된금액을 빼서 얼만큼 할인되었는지 금액을 구한다.
const percent = (discount / regularPrice) * 100; //toFixed:소수점자리제외/할인된금액의 %구하기/.toFixed(0) 는 소수점을 반올림해서 안되고 아래 Math.floor로 진행
return Math.floor(percent);
}
다른 파일에서 map을 통해 값을 얻어올 때 위 함수에 인자를 넣어 사용했다.
..
{calculatePercent(item.price, item.discountPrice)}%