VBA:四舍五入到数字的最接近倍数

编程入门 行业动态 更新时间:2024-10-14 08:27:08
本文介绍了VBA:四舍五入到数字的最接近倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此有关C ++的问题语言,但我需要VBA函数.我尝试将C ++函数转换为VBA,但没有返回正确的值.

This question has already been asked for the C++ language but I need a function for VBA. I tried converting the C++ function to VBA but it doesn't return the right values.

我需要一个执行以下操作的函数:

I need a function that does the following:

RoundUp(23.90, 5) 'return 25 RoundUp(23.90, 10) 'return 30 RoundUp(23.90, 20) 'return 40 RoundUp(23.90, 50) 'return 50 RoundUp(102.50, 5) 'return 105 RoundUp(102.50, 20) 'return 120

这是我到目前为止所拥有的.它在大多数情况下都有效,但是对于小于倍数的.5的数字,返回错误的值.因此,问题似乎是如何计算余数的舍入问题.

Here's what I have so far. It works most of the time but returns incorrect values for numbers that are less than .5 less than the multiple. So the problem seems to be a rounding problem with how I'm calculating the remainder value.

Public Function RoundUp(dblNumToRound As Double, lMultiple As Long) As Double Dim rmndr As Long rmndr = dblNumToRound Mod lMultiple If rmndr = 0 Then RoundUp = dblNumToRound Else RoundUp = Round(dblNumToRound) + lMultiple - rmndr End If End Function

例如:

RoundUp(49.50, 50) 'Returns 49.50 because rmndr = 0

推荐答案

我只需除以lMultiple,四舍五入并再次相乘即可.

I'd simply divide by the lMultiple, round up and multiply again.

假设您确实总是想四舍五入(对于负数也是如此):

Assuming you indeed always want to round up (also for negative numbers):

Public Function RoundUp(dblNumToRound As Double, lMultiple As Long) As Double Dim asDec as Variant Dim rounded as Variant asDec = CDec(dblNumToRound)/lMultiple rounded = Int(asDec) If rounded <> asDec Then rounded = rounded + 1 End If RoundUp = rounded * lMultiple End Function

我实际上不是VBA程序员,因此这可能需要调整一个或两个逗号.但是重要的是:

I'm not actually a VBA programmer, so this might need a tweaked comma or two. However the important thing is:

  • 使用十进制(变量子类型)以提高精度
  • 让VB为您做数学

更多推荐

VBA:四舍五入到数字的最接近倍数

本文发布于:2023-11-07 23:25:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567717.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:倍数   最接近   四舍五入   数字   VBA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!