Balaji M.H
Balaji M.H

Reputation: 21

How to assign a floating-point number to a variable in CMD?

When I write it as set /p=7.34 it is considering only 7 but not 7.34. How can I set a variable to a floating-point number?

Upvotes: 2

Views: 6647

Answers (2)

Aacini
Aacini

Reputation: 67236

Well, a small comment first: you may assign any floating-point number to a variable in CMD. The problem is when you want to perform arithmetic operations with such variable preserving decimal places.

I copied the following answer from this post:

Perform operations using fixed point arithmetic in Batch is simple. "Fixed point" means that you must set a number of decimals in advance and keep it throughout the operations. Add and subtract operations between two Fixed Point numbers are performed directly. Multiply and division operations requires an auxiliary variable, that we may call "one", with the value of 1 with the right number of decimals (as "0" digits). After multiply, divide the product by "one"; before division, multiply the dividend by "one". Here it is:

@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"

:getNumber
set /P "numA=Enter a number with %decimals% decimals: "
if "!numA:~-%decimalsP1%,1!" equ "." goto numOK
echo The number must have a point and %decimals% decimals
goto getNumber

:numOK
set numB=2.54

set "fpA=%numA:.=%"
set "fpB=%numB:.=%"

set /A add=fpA+fpB, sub=fpA-fpB, mul=fpA*fpB/one, div=fpA*one/fpB

echo %numA% + %numB% = !add:~0,-%decimals%!.!add:~-%decimals%!
echo %numA% - %numB% = !sub:~0,-%decimals%!.!sub:~-%decimals%!
echo %numA% * %numB% = !mul:~0,-%decimals%!.!mul:~-%decimals%!
echo %numA% / %numB% = !div:~0,-%decimals%!.!div:~-%decimals%!

For example:

Enter a number with 2 decimals: 3.76
3.76 + 2.54 = 6.30
3.76 - 2.54 = 1.22
3.76 * 2.54 = 9.55
3.76 / 2.54 = 1.48

Upvotes: 3

SachaDee
SachaDee

Reputation: 9545

Using a BAT/PS script :

@echo off
for /f  "delims=" %%x in  ('powershell 33.44 * 45.47') do echo %%x
pause

Upvotes: 3

Related Questions