toFixed(), toPrecision()

윤지영·2023년 7월 17일
0

소수점 자릿수 지정하기

메소드의미반환
숫자값.toFixed([자릿수])소수점 이하 자릿수 지정string 문자열
숫자값.toPrecision([자릿수])자릿수 지정 정밀도 반환string 문자열

Number.prototype.toFixed()

  • toFixed() 메서드는 숫자를 고정 소수점 표기법(fixed-point notation)으로 표시
  • toFixed()는 Number 객체를 주어진  숫자만큼의 소수점 이하 자리수를 정확하게 갖는 문자열 표현으로 반환. 소수점 이하가 길면 숫자를 반올림하고, 짧아서 부족할 경우 뒤를 0으로 채울 수 있다.
const num1 = 0.123
const num2 = 0.123

console.log(typeof (num1 + num2).toFixed(1)) //string
console.log(typeof Number((num1 + num2).toFixed(1))) //number

//toFixed()는 문자열 표현으로 반환!!! 
//문자열 데이터를 숫자 데이터로 변환하려면 Number, parseInt, parseFloat 사용!

console.log(Number((num1 + num2).toFixed(1))) //0.2
//Number(value)처럼 함수로 사용하면 문자열이나 다른 값을 Number 타입으로 변환. 
//만약 만약 인수를 숫자로 변환할 수 없으면 NaN을 리턴.

console.log(parseInt((num1 + num2).toFixed(1))) //0  
// parseInt() 함수는 문자열 인자를 파싱하여 특정 진수의 *정수*를 반환.

console.log(parseFloat((num1 + num2).toFixed(1))) //0.2 
// parseFloat() 함수는 주어진 값을 필요한 경우 문자열로 변환한 후 부동소수점 *실수*로 파싱해 반환.

console.log((num1 + num2).toFixed(2))//0.25 (반올림!!!)

let num = num1.toFixed(2) + 1;
console.log(num); // 0.121
// 1.12(0.12 + 1)가 아님!!!
// 문자열로 반환되고 이 문자열 뒤에 1을 이어 붙여 1.121

소수점 자릿수 지정

var numObj = 12345.6789;

numObj.toFixed();       // Returns '12346': 반올림하며, 소수 부분을 남기지 않습니다.
numObj.toFixed(1);      // Returns '12345.7': 반올림합니다.
numObj.toFixed(6);      // Returns '12345.678900': 빈 공간을 0으로 채웁니다.
(1.23e+20).toFixed(2);  // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2);  // Returns '0.00'
2.34.toFixed(1);        // Returns '2.3'
2.35.toFixed(1);        // Returns '2.4'. 이 경우에는 올림을 합니다.
-2.34.toFixed(1);       // Returns -2.3 (연산자의 적용이 우선이기 때문에, 음수의 경우 문자열로 반환하지 않습니다...)
(-2.34).toFixed(1);     // Returns '-2.3' (...괄호를 사용할 경우 문자열을 반환합니다.)

Number.prototype.toPrecision()

toPrecision() 메서드는 [Number](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number) 객체를 지정된 정밀도로 나타내는 문자열을 반환.

var numObj = 5.123456;

console.log(numObj.toPrecision());    // logs '5.123456'
console.log(numObj.toPrecision(5));   // logs '5.1235'
console.log(numObj.toPrecision(2));   // logs '5.1'
console.log(numObj.toPrecision(1));   // logs '5'

numObj = 0.000123

console.log(numObj.toPrecision());    // logs '0.000123'
console.log(numObj.toPrecision(5));   // logs '0.00012300'
console.log(numObj.toPrecision(2));   // logs '0.00012'
console.log(numObj.toPrecision(1));   // logs '0.0001'

.toFixed() 와 .toPrecision() 비교

var num = new Number(1.232323);
alert(num.toPrecision()); // string, 1.232323
alert(num.toPrecision(1)); // string, 1
alert(num.toPrecision(10)); // string, 1.232323000
 
alert(num.toFixed()); // string, 1
alert(num.toFixed(1)); // string, 1.2
alert(num.toFixed(10)); // string, 1.2323230000

** 15초간 카운트다운하는 샘플 만들기

:남은 밀리초(ms) 단위의 시간/1000’과 toFixde(2)를 통해 남은 시간을 소수점 두 자리 단위까지 계산해 반환한다.

자바스크립트코드레시피 278_p.92

https://codepen.io/developer-jyyun/pen/wvQmeJP

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>15초간 카운트다운하는 샘플 만들기/title>
    <style>

    </style>
</head>
<body>
<div class="timer">
    <div class="second"></div>
</div>    
</body>
<script>

    //## ** 15초간 카운트다운하는 샘플 만들기
    // 남은 밀리초(ms) 단위의 시간/1000’과 toFixde(2)를 통해 남은 시간을 소수점 두 자리 단위까지 계산해 반환한다.
    // 초단위용 element
    const secondElement = document.querySelector('.second');

    //15초를 목표치로 지정
    const goalTime = new Date().getTime() + 15 * 1000;
    update();

    //프레임 실행하는 함수

function update(){
    //현재시각
    const CurrentTime = new Date().getTime();

    //목표치까지 남은 시간
    const leftTime = goalTime - CurrentTime;

    //초 단위 표시. 밀리초는 소수점 두 자리까지
    secondElement.innerText = (leftTime / 1000).toFixed(2);

    // 프레임에서 update() 재실행
    requestAnimationFrame(update);
}
</script>

</html>

::심화 활용:: Dday타이머
https://sisiblog.tistory.com/342

참고페이지

MDN_toFixed()

mdn_toPrecision()

생활코딩

**[JS] 숫자 데이터 (toFixed, .abs, .min, .max, .ceil, .floor, round, random)**

[[javascript] 자바스크립트 카운드다운 타이머 (countdown timer)](https://sisiblog.tistory.com/342)

profile
쑥쑥쑥쑥 레벨업🌱🌼🌳

0개의 댓글