JavaScript toFixed メソッドを使って固定小数点数形式で文字列に変換する

環境
Google Chrome 109.0.5414.120
Windows 10 Home 64bit

書式
数値.toFixed([小数点の後の桁数])
Number オブジェクトの toFixed メソッドは、対象の数値を固定小数点数形式で表した文字列を返します。
数値を固定小数点数形式で表した文字列を返します。小数点数の前の桁は元の数値のまま、小数点の後の桁は引数で指定した数となります。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let nn = 56.4672;
console.log(nn.toFixed());
console.log(nn.toFixed(1));
console.log(nn.toFixed(3));
let nn = 56.4672; console.log(nn.toFixed()); console.log(nn.toFixed(1)); console.log(nn.toFixed(3));
let nn = 56.4672;

console.log(nn.toFixed());
console.log(nn.toFixed(1));
console.log(nn.toFixed(3));

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
> "56"
> "56.5"
> "56.467"
> "56" > "56.5" > "56.467"
> "56"
> "56.5"
> "56.467"

 

JavaScript

Posted by arkgame