批处理程序中小数的准确性

时间:2017-05-24 23:14:24

标签: batch-file

尝试创建一个可以接受十进制输入的批处理程序(我没有其他选项但只使用批处理),输入只能指定最多两个小数位。我的问题是如何舍入输出以提高准确性。例如用户输入是100.77 * 0.80,答案是80.616,我只能输出80.61而不是80.616,我想输出80.62。而我更大的问题是,十进制答案将用于从原始数量中减去,这将导致十进制级别的数学错误。答案是80.61和20.16。 这是我的计划:

@echo off
setlocal EnableDelayedExpansion

set decimals=2
set /A one=1, decimalsP1=decimals+1

for /L %%i in (1,1,%decimals%) do set "one=!one!0"

:getFee
set /P "Amt=Enter the Amount (100.00): "
set /P "Disc=Enter the Discount Percentage: "
if "!Amt:~-%decimalsP1%,1!" equ "." goto AmtDeci

:getNumber
goto NoDeci

:AmtDeci
set "fpA=%Amt:.=%"
set "fpB=%Disc:.=%"
set /A mul=fpA*fpB/one
set discout=!mul:~0,-2!.!mul:~-2!
echo The Discount is: %discout%
set /A "fpD=%discout:.=%"
set /A sub=fpA-fpD
set Amtout=!sub:~0,-%decimals%!.!sub:~-%decimals%!
echo The Amount less discount is: %Amtout%
pause
Exit /B
:NoDeci
set /a discout=%Amt%*%Disc%/100
set /a Amtout=%Amt%-discout
echo The Amount less Discount is: %Amtout%
echo The Discount is: %discout%
pause

1 个答案:

答案 0 :(得分:2)

我假设您使用的是this answer中描述的方法。您始终应该包含指向代码原始来源的链接。

你想要做的事情非常简单:只需在乘法结果中加上相应的0.5,然后再除以one

set /A mul=(fpA*fpB+50)/one

输出示例:

Enter the Amount (100.00): 100.77
Enter the Discount Percentage: 80
The Discount is: 80.62
The Amount less discount is: 20.15