VBScript 除法 - 自动将结果四舍五入到小数点后两位
我正在尝试将十进制数转换为十六进制数,内置的十六进制函数仅限于 8 个字符,因此我必须编写自己的函数,但是 VBScript 似乎将数字四舍五入到小数点后两位。
例如。
106681252129194 / 16 = 6667578258074.625
问题是当我在 VBScript 中执行此代码时,
strResult = 106681252129194 / 16
结果是 6667578258074.63,这使得计算十六进制数字成为一个小问题。
I'm trying to convert a decimal number to hex, the inbuilt Hex function is limited to 8 characters so I'm having to write my own function, however VBScript seems to be rounding the number to 2 decimal places.
So for example.
106681252129194 / 16 = 6667578258074.625
the problem is when I do it in VBScript this code
strResult = 106681252129194 / 16
the result is 6667578258074.63, which makes calculating the hex digit a slight issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须进行整数除法和余数运算。受邀查看我对 ascii 函数的数字 (double < 2^50) 的尝试:
基本测试代码:
输出:
顺便说一句 - 你不能使用 \:
You have to do an integer divison and remainder operation. Be invited to check out my attempt at a number (double < 2^50) to ascii function:
Basic test code:
Output:
BTW - you can't use \:
您超出了
Double
类型提供的精度,即 8 个字节。除法实际上并不是自动四舍五入到小数点后两位;而是将结果自动舍入到小数点后两位。只是您的小数点后第三位以上无处可去,因此四舍五入。
一种解决方案是使用
Decimal
类型,它提供14字节的存储空间。注:以上内容适用于VB。在 VBA 和 VBScript 中,
Decimal
类型只能在Variant
中访问。您不能直接声明Decimal
类型的变量;您必须创建一个Variant
,然后使用CDec
函数将其子类型设置为Decimal
:谨慎行事还是有好处的...
Decimal
将为您提供 28-29 个有效数字,而Double
将为您提供 14-15 个有效数字。另一方面,Double
为您提供了在 -324 到 +308 之间的 10 次幂的灵活性,如科学记数法中的那样,而使用Decimal
时,您只能使用直数符号,没有 10 的幂。You're exceeding the precision offered by type
Double
, i.e. 8 bytes.It isn't really that division auto-rounds things to 2 decimal places; it's just that your 3rd+ decimal places have nowhere to go and are therefore rounded out.
One solution is to use type
Decimal
, which offers 14 bytes of storage space.Note: The above is for VB. In VBA and VBScript, the
Decimal
type is only accessible within aVariant
. You can't directly declare a variable of typeDecimal
; you have to create aVariant
and then make its subtypeDecimal
using theCDec
function:It's still good to be cautious...
Decimal
will give you 28-29 significant figures, whileDouble
gives you only 14-15. On the other hand,Double
gives you the flexibility of a power of 10 between -324 and +308 as in the scientific notation, while withDecimal
you're stuck with straight notation, no powers of 10.