Use the math.Trunc function to truncate a floating point number into an integer part and return the truncated floating point number
Floating point number is a data type used in computers to represent real numbers (including integers and decimals). However, in practical applications, sometimes we only care about the integer part of the floating point number, and hope to truncate the floating point number and get an integer result. At this time, we can use the Trunc function in the math package to achieve this.
The Trunc function is a function in the math package of the Go language (Golang) standard library. It is used to truncate floating-point numbers into integer parts and return the truncated floating-point numbers.
The following is a code example that shows how to use the math.Trunc function to truncate a floating point number into an integer part:
package main import ( "fmt" "math" ) func main() { // 定义一个浮点数 num := 3.1415926 // 使用math.Trunc函数截断浮点数为整数部分 truncatedNum := math.Trunc(num) // 输出结果 fmt.Printf("浮点数 %.4f 的整数部分是 %.0f ", num, truncatedNum) }
In the above code, we define a floating point number num and use The math.Trunc function truncates it to the integer part and assigns it to truncatedNum. Then, we output the integer part of the floating point number num through the fmt.Printf function.
When running the program, the terminal will output the following results:
浮点数 3.1416 的整数部分是 3
As can be seen from the output results, the floating point number 3.1416 is truncated to obtain the integer 3.
It should be noted that the math.Trunc function only truncates the decimal part of the floating point number, and the returned result is a floating point number type, not an integer type. If we need to get an integer type result, we can use type conversion to convert the floating point number to an integer, such as using the int function:
intTruncatedNum := int(truncatedNum)
The above is to use the math.Trunc function to truncate the floating point number into the integer part and return Methods and code examples for truncated floating point numbers. Using this function, we can easily truncate floating point numbers to get the integer result we need.
The above is the detailed content of Use the math.Trunc function to truncate a floating point number into its integer part and return the truncated floating point number.. For more information, please follow other related articles on the PHP Chinese website!