달나라 노트

Google Apps Script : toPrecision (n자리의 숫자 string으로 변환) 본문

Google Apps Script

Google Apps Script : toPrecision (n자리의 숫자 string으로 변환)

CosmosProject 2022. 11. 29. 00:46
728x90
반응형

 

 

 

toPrecision method는 어떤 숫자를 받아서 이 숫자를 n자리만 나타내도록 잘라서 string으로 변환해줍니다.

 

 

Syntax

Number.toPrecision(n)

 

toPrecision method는 위처럼 어떠한 숫자에 적용할 수 있습니다.

 

- n

toPrecision method는 어떠한 숫자를 parameter로 받습니다.

이 숫자는 숫자를 몇 자리 까지 나타낼지를 의미합니다.

 

 

 

 

 

function myFunction(){
  var num = 7777.7777777777;

  var num_toprecisioned = num.toPrecision(6);

  Logger.log(num_toprecisioned);
  Logger.log(typeof(num_toprecisioned));
}


-- Result
7777.78
string

 

위 예시를 봅시다.

num 변수에 7777.7777777777이라는 숫자를 할당했습니다.

 

- var num_toprecisioned = num.toPrecision(6);

그리고 이 숫자에 toPrecision method를 적용했습니다.

 

parameter로서 6이 주어졌으므로 정수부와 소수부를 합해서 총 여섯 자리까지만 나타낸다는 의미입니다.

 

7777.78

그래서 결과를 보면 7777.78입니다.

총 6개의 숫자가 있으며 그 이하로는 반올림하여 없애버렸습니다.

 

 

- typeof(num_toprecisioned)

또한 이 부분을 보면 toPrecision의 결과는 숫자가 아닌 string type인 것을 알 수 있습니다.

 

 

 

 

 

 

728x90
반응형
Comments