Skip to content

Clarify rounding for snapped* functions #12113

Description

@charjr

Your Godot version:

4.7

Issue description (describe via experience):

I look at round:

Rounds x to the nearest whole number, with halfway cases rounded away from 0.

  • roundf(-0.5) # -1.0 yep, further from zero.
  • roundf(0.5) # 1.0 further from zero, all good here.

Then I look at snapped and its derivatives:

Returns the multiple of step that is the closest to x. This can also be used to [ROUND] a floating-point number to an arbitrary number of decimals.

There's no mention of how it rounds a number, but it used the word "round" so I figure behaviour matches round a.k.a. "away from zero".

  • snappedf(0.5, 1.0) # 1.0 yep, further from zero.
  • snappedf(-0.5, 1.0) # 0.0 oh?
  • snappedf(-0.5, -1.0) # -1.0 it's based on the step, maybe?

Looking at the implementation, I see how this occurs (even if I don't know the reasoning behind the implementation).

double Math::snapped(double p_value, double p_step) {
	if (p_step != 0) {
		p_value = Math::floor(p_value / p_step + 0.5) * p_step;
	}
	return p_value;
}

So I've pieced it together, but it required digging into the C++ which shouldn't be a requirement.

Solution

Document that halfway cases are rounded up for a positive step and down for a negative step

URL to the documentation page (if already existing):

https://docs.godotengine.org/en/stable/classes/class_%40globalscope.html#class-globalscope-method-snapped

Related Code:

implementation: math_funcs.cpp

docs: GlobalScope.xml

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:class referenceIssues and PRs about the class reference, which should be addressed on the Godot engine repository

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions