1

I need to get the last 2 digits of integers and decimals.

I'm using number%100 operator to get the last 2 digits of an integer. However, I get an error when I try the same on a decimal.

Is there any simple way to do it, without converting to a string and parsing?

Example:

number = 1234.56789

I need to get 89.

56789 % 100 = 89

1234.56789 % 100 gives error:

ValueError: invalid literal for int() with base 10

More examples:

number = 0.1 

I need to get 0.1 (with the decimal).

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Emily
  • 2,129
  • 3
  • 18
  • 43
  • Hmmm... by "last two digits" do you mean that the last 2 digits of 1013.145 would be 13? Or 45? – s.py Mar 20 '16 at 20:37
  • Do you know how many digits beyond the decimal the number will have? Or perhaps a maximum beyond the decimal? – s.py Mar 20 '16 at 20:53
  • What would be last two digits in case when number is [`0.1 + 0.2`](http://stackoverflow.com/questions/588004/is-floating-point-math-broken)? _(Note: expression is a link)._ Will it be `30` or `04`? – Łukasz Rogalski Mar 20 '16 at 20:53
  • I think @Rogalski is asking about the issue of [Floating Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). `0.1 + 0.2` will actually return `0.30000000000000004`. Would you want 0.3 or 04 from that? – s.py Mar 20 '16 at 20:59
  • @s.py I just want to point-out some non-trivialities about this task, actual "last two" significant digits in floating-point number may differ significantly from intuitive "obviously-it-should-be-x-why-should-it-be-different" approach. – Łukasz Rogalski Mar 20 '16 at 21:08
  • I would want 0.3 in that case. The number will be rounded first. Then the last 2 digits extracted. – Emily Mar 20 '16 at 21:08

2 Answers2

5

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:

89
23
0.1
1
0.3
4.5
1.4
DevLounge
  • 8,313
  • 3
  • 31
  • 44
Querenker
  • 2,242
  • 1
  • 18
  • 29
  • Yes, this works. This IS the right answer. Deleting mine as soon as yours is marked as correct answer as I cannot until the OP changes his vote. – DevLounge Mar 20 '16 at 21:53
0

I did this in a little different way, may be helpful.

# Finding last two digits of a number whether decimal or integer

def number(num):
    if type(num) == float:
        last_two_digit = str(num)[-2:]  # If float, make it string and cut last two digit
        return int(last_two_digit)   # convert back into integer and then return
    else:
        last_two_digit = num%100  # If integer, find the mode by 100
        return last_two_digit 
    
number(45.6912)
# Ans : 12

number(12548)
# Ans : 48
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83