简体   繁体   English

如何使用 AutoHotKey 脚本将数字(价格)转换为 0.05 的倍数?

[英]How to convert number (price) in to multiples of 0.05 using AutoHotKey script?

I was automating a trading software using AHK script.我正在使用 AHK 脚本自动化交易软件。 During price submission the app does not accept in between values, say between 1.50 and 1.55.在提交价格期间,应用程序不接受介于 1.50 和 1.55 之间的值。 It only accepts multiples of 0.05 because its tick-size is 0.05 hence i have to do the price conversion using AHK script.它只接受 0.05 的倍数,因为它的刻度大小是 0.05,因此我必须使用 AHK 脚本进行价格转换。

You can just use你可以使用

Round(N / 0.05) * 0.05

Example例子

Round(1.53 / 0.05) * 0.05 ; Returns 1.55

Explanation解释

I'm going to explain with 0.01 because it's easier to visualize, but it applies to any number.我将用 0.01 进行解释,因为它更容易可视化,但它适用于任何数字。 The number to round is 1.234.要四舍五入的数字是 1.234。 Anything after 3 will need to be discarded in the rounding process. 3 之后的任何内容都需要在舍入过程中丢弃。

If we divide the number 1.234 by 100, we get 123.4.如果我们将数字 1.234 除以 100,我们得到 123.4。 Note how the period is after 3. So we can just use Round now.注意期间是如何在 3 之后的。所以我们现在可以使用Round

After rounding, the number is 123. Now we just need to scale it back down by multiplying by 0.01, which results in 1.23.四舍五入后,数字为 123。现在我们只需将其缩小,乘以 0.01,即为 1.23。

Formatting格式化

As 0x464e pointed out in the comments, due how floating-point numbers work, the result may be imprecise.正如0x464e在评论中指出的那样,由于浮点数的工作方式,结果可能不精确。 So if you're going to convert them to strings, do so using Format("{:.2f}", number) .因此,如果您要将它们转换为字符串,请使用Format("{:.2f}", number)

The 2 comes from the minimum number of decimal places needed to accurately represent any number multiple of 0.05. 2来自准确表示 0.05 的任何倍数所需的最小小数位数。 By the way, this can be calculated by using:顺便说一句,这可以通过使用来计算:

Ceil(Log(1 / 0.05)) ; Returns 2

The following AHK function Roundoff converts and returns the price in its nearest tick-size multiple.以下 AHK function 舍入转换并返回其最接近的刻度大小倍数的价格。

Roundoff(price) ;round off to nearest 5 paisa value
{
    price := Round(price, 2) ;ronded to 2 decimal places
    priceNoDecimal := Floor(price)
    decimalPart :=  price - priceNoDecimal
    decimalPart := Floor( Round(decimalPart * 100, 2) )
    numerator := Floor(decimalPart / 5)
    remainder := Mod(decimalPart, 5)
    if ( remainder > 2)
        retval := (numerator * 5) + 5
    if ( remainder < 3)
        retval := (numerator * 5)
    retval := Round(priceNoDecimal + (retval / 100), 2)
    return retval
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM