﻿ How to Display Last 2 Digits from a Number in Python - ITCodar

# How to Display Last 2 Digits from a Number in Python

## How to get the last 2 digits of a number (integer or decimal)

Here is a working solution to your problem:

``def last_2_digits_at_best(n):    return float(str(n)[-3:]) if '.' in str(n)[-2:] else int(str(n)[-2:])print last_2_digits_at_best(1234.56789)print last_2_digits_at_best(123)print last_2_digits_at_best(0.1)print last_2_digits_at_best(1)print last_2_digits_at_best(0.1 + 0.2)``

Output:

``89230.110.34.51.4``

## How to print the last two digits of a 4 digit input taken by the user?

if you want the last two digits you can use `print(a[-2:])` since python uses negative index to start form the last item.
also check if the length of the input is greater than 2 characters.

``if len(a) >= 2:    print(a[-2:])``

## Sort a list of number by last 2 digits

You can get the last two digits using the remainder operator, then use the digits as key of sorted:

``a = [311, 409, 305, 104, 301, 204, 101, 306, 313, 202, 303, 410, 401, 105, 407, 408]result = sorted(a, key=lambda x: (x % 100, x))print(result)``

Output

``[101, 301, 401, 202, 303, 104, 204, 105, 305, 306, 407, 408, 409, 410, 311, 313]``

As you want to ties to be solved using the actual value the key is a tuple of the last two digits and the actual value.

## How to seperate last two digits with dot in Python

`300.00` is a representation of number `300`. `3.00` is a representation of number `3`. Those are two different values. There is no way Python will represent `300` as `3`.

Assuming you really want to print `3.00` (which for pretty much everyone around means `3`, not `300`), then you should divide `300` by `100`.

``print("{:.2f}".format(300/100.0))``

## How to make sure that in a string last 2 characters have at least one digit with python regex

Don't use `[A-Z0-9]{2}`, use `([A-Z0-9][0-9])|([0-9][A-Z0-9])`

That is, one or the other has to be a digit.

``re.findall(r'([A-Z]{5}(?:(?:[A-Z0-9][0-9])|(?:[0-9][A-Z0-9])))', "DHKGNC1, DHDHK32, DHKGN1K, SOME, GARBAGE, TEXT")['DHKGNC1', 'DHDHK32', 'DHKGN1K']``

Submit