四舍五入浮点数以设置分辨率

Rounding float decimals to set resolution

我有一个动画时间轴,其分辨率设置为 1 秒。

A resolution of 4 is (1000/4) which means that events are called every .25 .5 and .75th of a second.

我需要一种方法将用户输入的浮点数的小数四舍五入到设置的分辨率,以便我的时间线事件只能以分辨率中的数字开始和结束。

With a resolution of 4, 1.20 would round up to 1.25, 4.85 would be rounded down to 4.75, and 2.5 wouldn't be rounded

使用给定的相关浮点数和分辨率,最简单的方法是什么?

只需按 "resolution" 缩放您的值,四舍五入到最接近的整数,然后将其缩小,如下所示:

double originalValue = 1.2;
double resolution = 4;
double roundedValue;

roundedValue = Math.Round(originalValue * resolution, MidpointRounding.AwayFromZero) / resolution; // 1.25

MidpointRounding.AwayFromZero 选项需要得到 *.5 舍入 "up"(即远离零)。