Hướng dẫn how do i print the last 2 digits in python? - làm cách nào để in 2 chữ số cuối trong python?
With my code, I want to get the last two digits of an integer. But when I make x a positive number, it will take the first x digits, if it is a negative number, it will remove the first x digits. Show
Code:
asked Jan 15, 2017 at 18:37 0 Why don't you extract the absolute value of the number modulus 100? That is, use
to extract the last two digits? In terms of performance and clarity, this method is hard to beat. answered Jan 15, 2017 at 18:42
BathshebaBathsheba 229k33 gold badges353 silver badges473 bronze badges 0 To get the last 2 digits of 0 I would use a 1 line simple hack:
This would give a string. To get an int, just wrap with int:
answered Jan 15, 2017 at 19:13
Israel UntermanIsrael Unterman 12.7k4 gold badges27 silver badges34 bronze badges Simpler way to extract last two digits of the number (less efficient) is to convert the number to 1 and slice the last two digits of the number. For example:
OR, you may achieve it via using modulo 2 operator (more efficient), (to know more, check How does % work in Python?) as:
Sample run:
answered Jan 15, 2017 at 18:40
Moinuddin QuadriMoinuddin Quadri 44.9k12 gold badges93 silver badges119 bronze badges 2 to get the last 2 digits of an integer.
answered Oct 11, 2019 at 7:36
You can try this: float(str(num)[-2:]) answered Jan 7, 2021 at 22:38
Python code implementation without user defined functions & classesCode:# Python code to extract last two digits of a number a = 23457 a_string = str(a) a_length = len(a_string) c = int(a_string[a_length - 2: a_length]) print("The last two digit for the number: ", a, " is: ", c) |