Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify floating point decimal precision from variable?

I have the following repetitive simple code repeated several times that I would like to make a function for:

for i in range(10):
    id  = "some id string looked up in dict"
    val = 63.4568900932840928 # some floating point number in dict corresponding to "id"
    tabStr += '%-15s = %6.1f\n' % (id,val)

I want to be able to call this function: def printStr(precision)
Where it preforms the code above and returns tabStr with val to precision decimal points.

For example: printStr(3)
would return 63.457 for val in tabStr.

Any ideas how to accomplish this kind of functionality?

like image 336
Jeremy Avatar asked Apr 06 '11 22:04

Jeremy


People also ask

How can you assign a floating-point value to a variable?

Assigning Values (Putting Information in the Float Variables) You can then change the float value by assigning a value to the variable. (Just like you did with integers.) This is done simple by writing the variable name followed by an equals sign, followed by the value you want to put in the variable.

How do you find the precision of a floating-point?

The precision of floating-point numbers is either single or double, based on the number of hexadecimal digits in the fraction. A small integer is a binary integer with a precision of 15 bits. The range of small integers is -32768 to +32767. A large integer is a binary integer with a precision of 31 bits.

How do you present a decimal in a float value?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

What is precision of float type variable?

A variable of type float only has 7 digits of precision whereas a variable of type double has 15 digits of precision. If you need better accuracy, use double instead of float.


1 Answers

tabStr += '%-15s = %6.*f\n' % (id, i, val)  

where i is the number of decimal places.


BTW, in the recent Python where .format() has superseded %, you could use

"{0:<15} = {2:6.{1}f}".format(id, i, val)

for the same task.

Or, with field names for clarity:

"{id:<15} = {val:6.{i}f}".format(id=id, i=i, val=val)

If you are using Python 3.6+, you could simply use f-strings:

f"{id:<15} = {val:6.{i}f}"
like image 78
kennytm Avatar answered Oct 26 '22 19:10

kennytm