라이브러리

[JAVASCRIPT] num.toFixed(digits) - 지정된 소수점 자리까지 반올림하여 문자열 반환




toFixed() 메서드

JavaScript의 `toFixed()` 메서드는 숫자를 지정된 소수 자릿수까지 반올림하여 문자열로 반환합니다. 이 메서드는 `Number` 객체의 메서드이므로 숫자형 변수나 리터럴에 호출할 수 있습니다.

사용법


`toFixed(digits)` 메서드는 두 개의 매개변수를 받습니다.

- `digits`: 반올림하고 싶은 소수 자릿수입니다. 이 값은 0 이상의 정수여야 합니다.

예제


#hostingforum.kr
javascript

// 정수

let num = 123.456;

console.log(num.toFixed(0)); // 123

console.log(num.toFixed(1)); // 123.5

console.log(num.toFixed(2)); // 123.46

console.log(num.toFixed(3)); // 123.456

console.log(num.toFixed(4)); // 123.4560



// 소수

num = 123.4567;

console.log(num.toFixed(0)); // 123

console.log(num.toFixed(1)); // 123.5

console.log(num.toFixed(2)); // 123.46

console.log(num.toFixed(3)); // 123.457

console.log(num.toFixed(4)); // 123.4567

console.log(num.toFixed(5)); // 123.4567



주의사항


- `toFixed()` 메서드는 반올림을 수행하기 때문에 소수 자릿수가 지정된 경우 반올림이 수행됩니다.
- `toFixed()` 메서드는 문자열로 반환되므로 숫자형 변수에 할당할 때 주의해야 합니다.

대안


JavaScript에서 `toFixed()` 메서드를 대체할 수 있는 방법은 다음과 같습니다.

#hostingforum.kr
javascript

function toFixed(num, digits) {

  return num.toFixed(digits);

}



console.log(toFixed(123.456, 0)); // 123

console.log(toFixed(123.456, 1)); // 123.5

console.log(toFixed(123.456, 2)); // 123.46

console.log(toFixed(123.456, 3)); // 123.456

console.log(toFixed(123.456, 4)); // 123.4560



이 방법은 `toFixed()` 메서드와 동일한 결과를 반환합니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 7 페이지

검색

게시물 검색