Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to show only the decimal places

My code has shown well up to the second decimal place so far.

res4 = Decimal(‘%.2f’ % (res4 * 100 / 100))

but i got error…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

35.3169 –> 35.32

Why is it being raised?
I want to throw everything away from the third decimal place.
help bro!!!

>Solution :

If you don’t want to round numbers, you can truncate floats with string operations like this:

def truncate_number(num, limit):
  int_part, fract_part = str(float(num)).split('.')
  return float(f'{int_part}.{fract_part[:limit]}')

In [9]: truncate_number(35.3169, 2)
Out[9]: 35.31

In [9]: truncate_number(1.1199, 2)
Out[9]: 1.11

In [11]: truncate_number(1.1199, 3)
Out[11]: 1.119

In [11]: truncate_number(-1.1199, 3)
Out[11]: -1.119

Keep in mind that this function wont convert 1 to 1.000:

In [13]: truncate_number(1, 3)
Out[13]: 1.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading