[ JavaScript 08 ] Number 類型的內建函式


Posted by tzutzu858 on 2020-06-23

MDN 網站介紹 Number 有很多跟 Number 相關的內建函式,還有範例,很好用
MDN 網站介紹 Math


數字變字串

var a =10
a.toString() // 方法一
(a + ’ ’) // 方法二,加一個空字串

Number

  • Number 轉數字
    var a =10
    var b ='20'
    console.log(a+Number(b))
    

  • parseInt 轉數字,括弧後面參數可選擇多少進位
    var a =10
    var b ='20'
    console.log(a+parseInt(b))
    
    or
    var a =10
    var b ='10'
    console.log(a+parseInt(b,2))  // 2 代表 2 進位,也可以寫 10 進位、 16 進位......
    

  • parseFloat轉數字,包含小數
    var a =10
    var b ='20.352'
    console.log(a+parseFloat(b))
    

  • .toFixed(x)小數點後面太多,想要顯示前 x 位小數點就好,傳回來是字串,不傳任何參數則會把小數點都去掉
    var a =10
    var b ='20.353463575473632'
    console.log(a+parseFloat(b).toFixed(2))  //想要顯示前兩位小數
    // 印出會是 1020.35
    
    所以可以全括弧起來,再.toFixed(x)
    var a =10
    var b ='20.353463575473632'
    console.log((a+parseFloat(b)).toFixed(2))  //想要顯示前兩位小數
    // 印出會是 30.35
    

  • Number.MAX_VALUE 可以用在做判斷式
    if (x * y > Number.MAX_VALUE)
    

Math

  • Math.PI PI是常數,不會變,通常用大寫來表示
  • Math.ceil ceil 天花板,往上取,就是無條件進位
    console.log(Math.ceil(10.6)) // 印出 11
    
  • Math.floor 往下取,就是無條件捨去
    console.log(Math.floor(10.6))  // 印出 10
    
  • Math.round 四捨五入
    console.log(Math.round(10.6))  // 印出 11
    
  • Math.sqrt 開根號
    console.log(Math.sqrt(9))  // 印出 3
    
  • Math.pow 次方
    console.log(Math.pow(9,2)) // 9 的 2 次方
    
  • Math.random 隨機數 0 ~ <1
    console.log(Math.random()) 
    console.log(Math.floor(Math.random()*10+1))  // 取 1 ~ 10 的整數
    

#javascript







Related Posts

再戰 todo list 與其他 hooks

再戰 todo list 與其他 hooks

Python Type Annotations for a Generator

Python Type Annotations for a Generator

Lecture 1 Introduction to Radar Systems and Applications

Lecture 1 Introduction to Radar Systems and Applications


Comments