Related Articles

Related Articles

Python | Ways to format elements of given list
  • Last Updated : 01 Mar, 2019

Given a List of float values, the task is to truncate all float values to 2-decimal digit. Let’s see the different methods to do the task.

Method #1 : Using List comprehension

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to truncate float
# values to 2-decimal digits.
  
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
  
# Using list comprehension
Output = ["%.2f" % elem for elem in Input]
  
# Printing output
print(Output)

chevron_right


Output:

['100.77', '17.23', '60.99', '300.84']

 
Method #2 : Using Map

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to truncate float 
# values to 2 decimal digits.
  
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
  
# Using map
Output = map(lambda n: "%.2f" % n, Input)
  
# Converting to list
Output = list(Output)
  
# Print output
print(Output)

chevron_right


Output:



['100.77', '17.23', '60.99', '300.84']

 
Method #3 : Using format

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to truncate float
# values to 2 decimal digits.
  
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
  
# Using forrmat
Output = ['{:.2f}'.format(elem) for elem in Input]
  
# Print output
print(Output)

chevron_right


Output:

['100.77', '17.23', '60.99', '300.84']

 
Method #4 : Using Iteration

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to truncate float
# values to 2 decimal digits.
  
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
  
# Output list initialization
Output = []
  
# Iterating
for elem in Input:
    Output.append("%.2f" % elem)
  
# Printing output
print(Output)

chevron_right


Output:

['100.77', '17.23', '60.99', '300.84']

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :