在C#中,我希望将双精度舍入到较低的精度,以便我可以将它们存储在关联数组中的不同大小的存储桶中.与通常的舍入不同,我想要舍入到一些重要的位.因此,大数字的绝对值会比小数字更改,但它们往往会按比例改变.因此,如果我想要舍入到10个二进制数字,我会找到十个最高有效位,并将所有低位都清零,可能会添加一个小数字进行舍入.
我更喜欢将"中途"数字四舍五入.
如果它是整数类型,这里可能是一个算法:
Run Code Online (Sandbox Code Playgroud)1. Find: zero-based index of the most significant binary digit set H. 2. Compute: B = H - P, where P is the number of significant digits of precision to round and B is the binary digit to start rounding, where B = 0 is the ones place, B = 1 is the twos place, etc. 3. Add: x = x + 2^B This will force a carry if necessary (we round halfway values up). 4. Zero …