roundf
2026/4/15大约 2 分钟
最后同步日期:2026-04-15 | Godot 官方原文 — roundf
roundf
定义
roundf() 将一个浮点数四舍五入到最近的整数,但返回值仍然是 float 类型。
就像买东西时的四舍五入——3.4 元算 3 元,3.6 元算 4 元。恰好卡在中间的 3.5 元呢?也往上算,算 4 元。简单来说就是"过半就进一"。
函数签名
C#
// C# 中使用 Mathf.Round()
// 注意:Mathf.Round 采用"银行家舍入"规则(MidpointRounding.ToEven)
// 如果需要与 GDScript 的 roundf() 行为一致,请使用 MidpointRounding.AwayFromZero
public static float Mathf.Round(float x)GDScript
func roundf(x: float) -> float参数说明
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
x | float | 是 | 需要四舍五入的浮点数值 |
返回值
float —— 四舍五入后的整数值,但类型仍然是 float(比如 3.6 返回 4.0,而不是整数 4)。
代码示例
C#
using Godot;
using System;
public partial class RoundExample : Node
{
public override void _Ready()
{
// 基本四舍五入
GD.Print(Mathf.Round(3.4f)); // 4(注意:C# 默认银行家舍入)
GD.Print(Mathf.Round(3.6f)); // 4
GD.Print(Mathf.Round(-3.4f)); // -4
GD.Print(Mathf.Round(-3.6f)); // -4
// 如果需要与 GDScript roundf() 完全一致的"四舍五入"行为
// 请使用 MidpointRounding.AwayFromZero
float RoundF(float x)
{
return (float)Math.Round(x, MidpointRounding.AwayFromZero);
}
GD.Print(RoundF(3.5f)); // 4(远离零的方向舍入)
GD.Print(RoundF(2.5f)); // 3(远离零的方向舍入,而非银行家舍入的 2)
GD.Print(RoundF(-2.5f)); // -3
}
}GDScript
extends Node
func _ready():
# 基本四舍五入
print(roundf(3.4)) # 3.0
print(roundf(3.6)) # 4.0
print(roundf(3.5)) # 4.0(过半进一)
print(roundf(-3.4)) # -3.0
print(roundf(-3.6)) # -4.0
print(roundf(-3.5)) # -4.0
# 返回值仍然是 float 类型
var result = roundf(5.7)
print(result) # 6.0
print(typeof(result)) # TYPE_FLOAT (3)注意事项
- 返回值类型是
float,不是int。如果你需要整数类型,请使用roundi()(GDScript)或自行转换为int。 - GDScript 的
roundf()采用"四舍五入远离零"规则(即0.5始终向上取绝对值更大的整数),而 C# 的Mathf.Round()默认采用"银行家舍入"规则(0.5舍入到最近的偶数)。如果 C# 项目需要与 GDScript 行为完全一致,请使用Math.Round(x, MidpointRounding.AwayFromZero)。 - 对于负数,
roundf(-0.5)返回-1.0(远离零的方向),而不是0.0。
