截斷(浮點數到浮點數)

trunc 指令,是 truncate(截斷)的縮寫,用於獲取數字的整數部分,捨棄小數部分。

當用於負數時,truncfloor 的不同之處在於:floor 會向下取整,而 trunc 會向零取整(向上舍入)。

還有另一個 trunc 指令,它會截斷浮點數的小數部分並將其轉換為整數。

試一試

(module
  (import "console" "log" (func $log (param f32)))
  (func $main

    f32.const -2.7 ;; load a number onto the stack
    f32.trunc ;; discard everything after the decimal point
    call $log ;; log the result

  )
  (start $main)
)
const url = "{%wasm-url%}";
await WebAssembly.instantiateStreaming(fetch(url), { console });

語法

wat
;; load a number onto the stack
f32.const 2.7

;; discard the fractional part (.7)
f32.trunc

;; the top item on the stack will now be 2
指令 二進位制操作碼
f32.trunc 0x8f
f64.trunc 0x9d