當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


d3.js precisionFixed()用法及代碼示例

D3.js中的d3.precisionFixed()函數用於根據給定的步長值返回固定浮點數表示法的十進製精度。

用法:

d3.precisionFixed(step);

參數:它僅采用上麵給出和下麵描述的一個參數。

  • Step:步長值表示小數點後需要多少位數,例如0.1表示輸出中的小數點後一位,而0.001表示小數點後的3位。

返回值:它返回一個數字。

下麵給出了above-given函數的一些示例。



範例1:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" 
        content="width=device-width,  
                 initial-scale=1.0"> 
  <title>Document</title> 
</head> 
<style> 
</style> 
<body> 
  <!--Fetching from CDN of D3.js -->
  <script type = "text/javascript"
          src = "https://d3js.org/d3.v4.min.js"> 
  </script> 
  <script> 
    let p=d3.precisionFixed(0.001); 
    let f=d3.format("."+p+"f"); 
    let roundedNumber=f(.12359); 
    console.log("Old number is:", 0.012345); 
    console.log("New number is:", roundedNumber); 
  </script> 
</body> 
</html>

輸出:

範例2:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" 
        content="width=device-width, 
                 initial-scale=1.0"> 
  <title>Document</title> 
</head> 
<style> 
</style> 
<body> 
  <!--Fetching from CDN of D3.js -->
  <script type = "text/javascript"
          src = "https://d3js.org/d3.v4.min.js"> 
  </script> 
  <script> 
    let p=d3.precisionFixed(0.005); 
    let f=d3.format("."+p+"f"); 
    let roundedNumber=f(.21543); 
    // Number of digits after decimal 
    console.log("Value of p is:", p); 
    console.log("Type of p is:", typeof p) 
    console.log("Old number is:", 0.21543); 
    console.log("New number is:", roundedNumber); 
  
    console.log("\n"); 
    p=d3.precisionFixed(1); 
    f=d3.format("."+p+"f"); 
    roundedNumber=f(2.21543); 
    // Number of digits after decimal 
    console.log("Value of p is:", p); 
    console.log("Old number is:", 0.21543); 
    console.log("New number is:", roundedNumber); 
  
      
    console.log("\n"); 
    p=d3.precisionFixed(0.01); 
    f=d3.format("."+p+"f"); 
    roundedNumber=f(.21543); 
    // Number of digits after decimal 
    console.log("Value of p is:", p); 
    console.log("Old number is:", 0.21543); 
    console.log("New number is:", roundedNumber); 
  
      
    console.log("\n"); 
    p=d3.precisionFixed(0.000002); 
    f=d3.format("."+p+"f"); 
    roundedNumber=f(.21543); 
    // Number of digits after decimal 
    console.log("Value of p is:", p); 
    console.log("Old number is:", 0.21543); 
    console.log("New number is:", roundedNumber); 
  </script> 
</body> 
</html>

輸出:




相關用法


注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 D3.js precisionFixed() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。