Movatterモバイル変換


[0]ホーム

URL:


  1. 開発者向けのウェブ技術
  2. JavaScript
  3. JavaScript リファレンス
  4. 標準組み込みオブジェクト
  5. Math
  6. trunc()

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。

View in EnglishAlways switch to English

Math.trunc()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

Math.trunc() 関数は、引数として与えた数の小数部の桁を取り除くことによって整数部を返します。

試してみましょう

console.log(Math.trunc(13.37));// 予想される結果: 13console.log(Math.trunc(42.84));// 予想される結果: 42console.log(Math.trunc(0.123));// 予想される結果: 0console.log(Math.trunc(-0.123));// 予想される結果: -0

構文

js
Math.trunc(x)

引数

x

数値。

返値

x の整数部です。

解説

Math.trunc() の処理は、他の 3 つのMath メソッド、Math.floor()Math.ceil()Math.round() よりも直感的です。引数が正の数か負の数かに関わらず、小数点とその右側の桁を切り詰め(切り捨て)ます。

trunc()Math オブジェクトの静的なメソッドなので、自ら生成したMath オブジェクトのメソッドとしてではなく、常に、Math.trunc() として使用してください (Math オブジェクトにはコンストラクタがありません)。

Math.trunc() の使用

js
Math.trunc(-Infinity); // -InfinityMath.trunc("-1.123"); // -1Math.trunc(-0.123); // -0Math.trunc(-0); // -0Math.trunc(0); // 0Math.trunc(0.123); // 0Math.trunc(13.37); // 13Math.trunc(42.84); // 42Math.trunc(Infinity); // Infinity

ビット単位の no-op を使った数値の切り捨て

警告:無視できないエッジケースがあるため、これはMath.trunc() のポリフィルにはなりません。

ビット演算はオペランドを32ビット整数に変換するため、従来は浮動小数点数を切り捨てるために利用されてきました。一般的なテクニックは以下の通りです。

js
const original = 3.14;const truncated1 = ~~original; // 二重否定const truncated2 = original & -1; // Bitwise AND with -1const truncated3 = original | 0; // Bitwise OR with 0const truncated4 = original ^ 0; // Bitwise XOR with 0const truncated5 = original >> 0; // Bitwise shifting by 0

これは本質的にtoInt32 であり、Math.trunc とは異なることに注意してください。値が -231 - 1 <value < 231 (-2147483649 <value < 2147483648) を満たさない場合、変換がオーバーフローしてしまいます。

js
const a = ~~2147483648; // -2147483648const b = ~~-2147483649; // 2147483647const c = ~~4294967296; // 0

Math.trunc() の代用として~~ を使うのは、入力の範囲が 32 ビット整数の範囲に収まっていると確信できる場合だけにしてください。

仕様書

Specification
ECMAScript® 2026 Language Specification
# sec-math.trunc

ブラウザーの互換性

関連情報

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp