roundi
2026/4/15大约 3 分钟
最后同步日期:2026-04-15 | Godot 官方原文 — roundi
roundi
定义
roundi() 是四舍五入取整函数,它的作用非常直白:把一个小数"四舍五入"到最近的整数,并且返回的结果是 int(整数)类型。
打个比方:你去超市买菜,称重显示 3.7 斤,收银员会按 4 斤算钱;如果显示 3.2 斤,就按 3 斤算。roundi() 就是这个"收银员"——看小数点后面第一位,大于等于 0.5 就往上进一位,小于 0.5 就舍去。
与 round() 的区别在于:round() 返回 float(浮点数),而 roundi() 返回 int(整数)。当你需要的是一个真正的整数(比如数组下标、循环计数器),用 roundi() 更方便,省去了手动类型转换。
函数签名
C#
// 方式一:使用 Godot 的 Mathf(推荐,直接返回 int)
public static int RoundToInt(float x)
// 方式二:先 Round 再手动转 int
(int)Mathf.Round(x)GDScript
func roundi(x: float) -> int参数说明
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
| x | float | 是 | 需要四舍五入的小数 |
返回值
类型: int
返回 x 四舍五入后的整数值。
| 输入 | 输出 | 说明 |
|---|---|---|
| 3.7 | 4 | 小数部分 >= 0.5,往上进位 |
| 3.2 | 3 | 小数部分 < 0.5,舍去 |
| 3.5 | 4 | 恰好 0.5,向远离零的方向进位 |
| -2.3 | -2 | 负数同理,-2.3 更接近 -2 |
| -2.7 | -3 | 负数同理,-2.7 更接近 -3 |
代码示例
下面是一个网格对齐的例子——在制作棋盘或塔防游戏时,需要把鼠标位置"吸附"到最近的网格点上:
C#
using Godot;
public partial class GridPlacer : Node2D
{
// 导出属性:每个网格单元的大小(像素)
[Export] public int ExCellSize = 64;
// 内部变量:当前鼠标所在的网格坐标
private Vector2I _gridPos;
public override void _Process(double delta)
{
// 获取鼠标在本地坐标系中的位置
Vector2 mousePos = GetLocalMousePosition();
// 把像素坐标除以格子大小,得到小数格坐标
// 然后用 roundi 四舍五入到最近的整数格子
int gridX = Mathf.RoundToInt(mousePos.X / ExCellSize);
int gridY = Mathf.RoundToInt(mousePos.Y / ExCellSize);
_gridPos = new Vector2I(gridX, gridY);
// 把格子坐标转回像素坐标,实现"吸附"效果
Vector2 snappedPos = new Vector2(
gridX * ExCellSize,
gridY * ExCellSize
);
GD.Print($"鼠标: {mousePos}, 吸附到网格: {snappedPos}, 格子坐标: {_gridPos}");
}
}GDScript
extends Node2D
## 导出属性:每个网格单元的大小(像素)
@export var ex_cell_size: int = 64
## 内部变量:当前鼠标所在的网格坐标
var _grid_pos := Vector2i.ZERO
func _process(delta: float) -> void:
# 获取鼠标在本地坐标系中的位置
var mouse_pos := get_local_mouse_position()
# 把像素坐标除以格子大小,得到小数格坐标
# 然后用 roundi 四舍五入到最近的整数格子
var grid_x := roundi(mouse_pos.x / ex_cell_size)
var grid_y := roundi(mouse_pos.y / ex_cell_size)
_grid_pos = Vector2i(grid_x, grid_y)
# 把格子坐标转回像素坐标,实现"吸附"效果
var snapped_pos := Vector2(
grid_x * ex_cell_size,
grid_y * ex_cell_size
)
print("鼠标: %s, 吸附到网格: %s, 格子坐标: %s" % [mouse_pos, snapped_pos, _grid_pos])注意事项
- 返回值是
int类型:这是roundi()和round()的唯一区别。round()返回float(如 4.0),roundi()返回int(如 4)。如果你需要把结果用作数组下标或循环索引,用roundi()更直接。 - "银行家舍入"问题:当小数部分恰好是 0.5 时,Godot 的
roundi()向远离零的方向舍入(即 2.5 变 3,-2.5 变 -3),而不是"四舍六入五成双"。这与 C# 的Mathf.Round()默认行为不同——C# 默认使用"银行家舍入"(MidpointRounding.ToEven)。如果需要在 C# 中复现 Godot 行为,请使用Mathf.RoundToInt()。 - 与
floori()/ceili()的对比:roundi(3.7)= 4(四舍五入)floori(3.7)= 3(永远向下取整)ceili(3.7)= 4(永远向上取整)
根据你的需求选择合适的函数。
