-1

I'm very new to batch script.

I'm getting this error and clueless how to solve. im supposed to get amount (ml) =9.375, but instead getting 5.

Im trying to come up with dose calculator

The whole idea is getting for right amount, weight is 15kg, dose is 15mg/kg. strenght of solution is 120mg/5ml.

So the amount is ((15*15)/120)*5=9.375ml

Where I might go wrong here?

@echo off
Title Syrup dose calculator
color 5a

set /p weight= Enter child's weight:
set /p dose= Enter required dose in mg/kg:
set /a totaldose= %weight%*%dose%
set /a amountml = ((%weight%*%dose%)/120)*5)
echo.
echo Total(mg) :%totaldose%
echo Amount(ml) : %amountml%

echo.
pause

goto loop
Anandapadmanathan
  • 315
  • 1
  • 3
  • 8
  • 1
    `set /a` does integer (INT32) only. No floating point operations in batch. – Stephan Sep 16 '22 at 16:51
  • This may help: https://stackoverflow.com/questions/1503888/floating-point-division-in-a-batch-file – Andrew Sep 16 '22 at 16:55
  • 1
    I told you that `Set /A` only worked with integers in [my comment](https://stackoverflow.com/questions/73744221/unable-to-get-correct-output-for-dose-calculator-with-bat-scripts#comment130219715_73744221>/) to your already open [question](https://stackoverflow.com/q/73744221), where I also told you it was the wrong tool for the task. – Compo Sep 16 '22 at 17:02
  • But you can multiply values by 1000 times before formula operations, then calculate **Amount**. And output values can be formatted by suitable point position: **set /a amountml=(1000*(15*15)/120)*5**; **set fractional=%amountml:~-3,3%:%**; **set /a amountml=amountml/1000** – Daemon-5 Sep 16 '22 at 17:07
  • 1
    And the [answer](https://stackoverflow.com/q/73744221), which you've seemingly ignored too, also suggested, and I agree, that you should use `* 5` prior to `/ 120`, as there is less chance of always having to multiply `0` by `5`, i.e result in `0` I also showed you the correct syntax for `Set /A`, which should be `weight * dose`, not `%weight% * %dose%`. `Set /A` will assume any non integer is a defined variable name, and use it if it is, _(or error if it isn't)_. So you should not ask cmd.exe to perform variable expansion, when it doesn't need to. – Compo Sep 16 '22 at 17:18

1 Answers1

0

There is no floating-point arithmetic in batch. set /a (which is the only thing in cmd that does arithmetic) can only handle Integers (to be exact: INT32). You can either write some messy code to do it "by hand" or use the help of another language (for example PowerShell) and get it's output with a for /f loop.

(Code simplified for demonstration)

@echo off
setlocal 

set weight=15
set dose=15
set /a totaldose=%weight%*%dose%
for /f "delims=" %%a in ('powershell %weight%*%dose%/120*5') do set amountml=%%a
echo Total(mg) : %totaldose%
echo Amount(ml) : %amountml%
Stephan
  • 53,940
  • 10
  • 58
  • 91