截断(浮点数到浮点数)

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