JavaScript

[JS] JS 숫자데이터(Number)

2023. 3. 15. 16:09
목차
  1. Number.prototype.toFixed()
  2. parseInt(), parseFloat() = (전역함수)
  3. Math.abs()
  4. Math.min()
  5. Math.max()
  6. Math.ceil()
  7. Math.floor()
  8. Match.round()
  9. Math.random()
728x90
반응형
const pi = 3.14159265358979
console.log(pi)

Number.prototype.toFixed()

toFixed() 메서드는 숫자를 고정 소수점 표기법(fixed-point notation)으로 표시합니다.

고정 소수점 표기법을 사용하여 나타낸 수를 문자열로 반환

const pi = 3.14159265358979
console.log(pi)

console.log(pi.toFixed(2))
// 3.14
// 소수점 두 자리만 남기고 제거
console.log(typeof str)
// String타입으로 출력
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' (...괄호를 사용할 경우 문자열을 반환합니다.)

parseInt(), parseFloat() = (전역함수)

parseInt()
함수는 문자열 인자를 파싱하여 특정 진수(수의 진법 체계에서 기준이 되는 값)의 정수를 반환합니다.

parseInt('0e0')  // 0
parseInt('08')   // 8

const integer = parseInt(srt)
console.log(integer) 
// 3

console.log(typeof integer)
//number

Number.parseFloat()
메서드는 주어진 값을 필요한 경우 문자열로 변환한 후 부동소수점 실수로 파싱해 반환합니다. 숫자를 파싱할 수 없는 경우 [NaN](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/NaN)을 반환합니다.

const float = parseFloat(str)
console.log(float)
// 3.14

console.log(typeof float)
//number

Math

Math는 수학적인 상수와 함수를 위한 속성과 메서드를 가진 내장 객체입니다. 함수 객체가 아닙니다.

Math.abs()

Math.abs() 함수는 주어진 숫자의 절대값을 반환합니다.

x가 양수이거나 0이라면 x를 리턴하고, x가 음수라면 x의 반대값, 즉 양수를 반환합니다.

Math.abs('-1');     // 1
Math.abs(-2);       // 2
Math.abs(null);     // 0
Math.abs('');       // 0
Math.abs([]);       // 0
Math.abs([2]);      // 2
Math.abs([1,2]);    // NaN
Math.abs({});       // NaN
Math.abs('string'); // NaN
Math.abs();         // NaN

Math.min()

Math.min() 함수는 주어진 숫자들 중 가장 작은 값을 반환합니다.

console.log('min: ', Math.min(2, 8))
// min: 2

Math.max()

Math.max() 함수는 입력값으로 받은 0개 이상의 숫자 중 가장 큰 숫자를 반환합니다.

console.log(Math.max(1, 3, 2));
// Expected output: 3

console.log(Math.max(-1, -3, -2));
// Expected output: -1

const array1 = [1, 3, 2];

console.log(Math.max(...array1));
// Expected output: 3

// ------------------------

Math.max(10, 20);   //  20
Math.max(-10, -20); // -10
Math.max(-10, 20);  //  20

문법

Math.max()
Math.max(값0)
Math.max(값0, 값1)
Math.max(값0, 값1, ... , 값N)

Math.ceil()

**Math.ceil()** 함수는 주어진 숫자보다 크거나 같은 숫자 중 가장 작은 숫자를 integer 로 반환합니다.

Math.ceil(.95);    // 1
Math.ceil(4);      // 4
Math.ceil(7.004);  // 8
Math.ceil(-0.95);  // -0
Math.ceil(-4);     // -4
Math.ceil(-7.004); // -7

Math.floor()

Math.floor() 함수는 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환합니다.

console.log(Math.floor(5.95));
// Expected output: 5

console.log(Math.floor(5.05));
// Expected output: 5

console.log(Math.floor(5));
// Expected output: 5

console.log(Math.floor(-5.05));
// Expected output: -6

Match.round()

Math.round() 함수는 입력값을 반올림한 수와 가장 가까운 정수 값을 반환합니다.

console.log(Math.round(0.9));
// Expected output: 1

console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
// Expected output: 6 6 5

console.log(Math.round(-5.05), Math.round(-5.5), Math.round(-5.95));
// Expected output: -5 -5 -6

Math.random()

Math.random() 함수는 0 이상 1 미만의 구간에서 근사적으로 균일한(approximately uniform) 부동소숫점 의사난수를 반환하며, 이 값은 사용자가 원하는 범위로 변형할 수 있다. 난수 생성 알고리즘에 사용되는 초기값은 구현체가 선택하며, 사용자가 선택하거나 초기화할 수 없다.

console.log('random: ', Math.random())
export default function ramdom(){
    return Math.floor(Math.random() * 10)
}

// 0부터 9까지의 난수를 임의로 구하는 식
728x90
반응형
저작자표시 비영리 변경금지 (새창열림)

'JavaScript' 카테고리의 다른 글

[JS] continue and break  (0) 2024.05.29
[JS] 배열API  (2) 2024.02.28
[JS] JS 문자데이터(String)  (0) 2023.03.15
[JS] JS 생성자와 프로토타입  (0) 2023.03.14
[JS] JS 스코프(Scope) 유효범위 가볍게 이해하기  (0) 2023.03.14
  1. Number.prototype.toFixed()
  2. parseInt(), parseFloat() = (전역함수)
  3. Math.abs()
  4. Math.min()
  5. Math.max()
  6. Math.ceil()
  7. Math.floor()
  8. Match.round()
  9. Math.random()
'JavaScript' 카테고리의 다른 글
  • [JS] continue and break
  • [JS] 배열API
  • [JS] JS 문자데이터(String)
  • [JS] JS 생성자와 프로토타입
우주방랑자 개자이너 박모나
우주방랑자 개자이너 박모나
개발자 디자이너가 되기 위해 그간 쌓은 물경력을 회복시키는 중입니다. 다양한 정보를 습득 중입니다 멋진 개자이너가 될겁니다.
250x250
우주방랑자 개자이너 박모나
우주방랑자 개자이너
우주방랑자 개자이너 박모나
전체
오늘
어제
  • 분류 전체보기 (23)
    • UIUX (1)
    • Figma (1)
    • JavaScript (10)
    • REACT (1)
    • CSS&SCSS (1)
    • HTML (1)
    • 10주완성 프로젝트 캠프 (8)

블로그 메뉴

    공지사항

    인기 글

    태그

    • 스나이퍼팩토리
    • 리액트
    • 피그마
    • 개발캠프
    • 인사이드아웃
    • 프로젝트캠프후기
    • 웅진씽크빅
    • react
    • figma
    • 개발자부트캠프
    • 유데미
    • IT개발자캠프
    • 프로젝트캠프
    • IT개발캠프

    최근 댓글

    최근 글

    hELLO · Designed By 정상우.
    우주방랑자 개자이너 박모나
    [JS] JS 숫자데이터(Number)
    상단으로

    티스토리툴바

    개인정보

    • 티스토리 홈
    • 포럼
    • 로그인

    단축키

    내 블로그

    내 블로그 - 관리자 홈 전환
    Q
    Q
    새 글 쓰기
    W
    W

    블로그 게시글

    글 수정 (권한 있는 경우)
    E
    E
    댓글 영역으로 이동
    C
    C

    모든 영역

    이 페이지의 URL 복사
    S
    S
    맨 위로 이동
    T
    T
    티스토리 홈 이동
    H
    H
    단축키 안내
    Shift + /
    ⇧ + /

    * 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.