このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
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() 関数は、引数として与えた数の小数部の桁を取り除くことによって整数部を返します。
In this article
試してみましょう
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構文
Math.trunc(x)引数
x数値。
返値
x の整数部です。
解説
Math.trunc() の処理は、他の 3 つのMath メソッド、Math.floor()、Math.ceil()、Math.round() よりも直感的です。引数が正の数か負の数かに関わらず、小数点とその右側の桁を切り詰め(切り捨て)ます。
trunc() はMath オブジェクトの静的なメソッドなので、自ら生成したMath オブジェクトのメソッドとしてではなく、常に、Math.trunc() として使用してください (Math オブジェクトにはコンストラクタがありません)。
例
>Math.trunc() の使用
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ビット整数に変換するため、従来は浮動小数点数を切り捨てるために利用されてきました。一般的なテクニックは以下の通りです。
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) を満たさない場合、変換がオーバーフローしてしまいます。
const a = ~~2147483648; // -2147483648const b = ~~-2147483649; // 2147483647const c = ~~4294967296; // 0Math.trunc() の代用として~~ を使うのは、入力の範囲が 32 ビット整数の範囲に収まっていると確信できる場合だけにしてください。
仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-math.trunc> |