Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a variable be used in Python to define decimal places

Tags:

I'm familiar with the convention of using %.2f to set two decimal places for a float but is it in any way possible to change the number to a variable so that the user can state the number of decimal places displayed?

like image 960
Kirk Rogers Avatar asked Mar 31 '13 10:03

Kirk Rogers


People also ask

Can a variable be a decimal?

At this time, the Decimal data type can only be used within a Variant; that is, you cannot declare a variable to be of type Decimal. You can, however, create a Variant whose subtype is Decimal by using the CDec function.

Can Python do decimals?

From Python 3.2 onwards, a Decimal instance can also be constructed directly from a float .


1 Answers

.format is a nicer, more readable way to handle variable formatting:

'{:.{prec}f}'.format(26.034, prec=3) 
like image 139
nneonneo Avatar answered Oct 25 '22 21:10

nneonneo