PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] How to keep trailing 0s when round a number in python?

 August 07, 2022     decimal, numpy, python, rounding     No comments   

Issue

I wanted to keep two decimal places after the decimal and keep the trailing 0s for example. 17.7 I want it to be 17.70, or 22.00. So, I have a list of numbers I want to return the maximum and round so that it fits that format.

list = [11, 12.3, 14, 200.33, 49.08, 207.2]

a = max(round(list), 2)

This is what I have done, but it still does not round all the points separately and keep the 2 decimal places. I am not tied to keeping round inside of max, I was just experimenting.


Solution

Short answer, you can't. Unless you modify the underlying object, you cannot change its representation. What you might want is a string formatted to look like this. Here are two approaches:

my_list = [11, 12.3, 14, 200.33, 49.08, 207.2]
['%.2f'%i for i in my_list]

output:

['11.00', '12.30', '14.00', '200.33', '49.08', '207.20']

f-strings (python >3.6):

[f'{i:.2f}' for i in my_list]

NB. do NOT call a list "list", this is already a python builtin



Answered By - mozway
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing