-3

How to show invert a decimal number in python?

n = 12.789

i want to show it like that.

print (n)

987.21

output:987.21

meti
  • 3
  • 2
  • 4
    Have you tried anything yet? Where exactly are you stuck? – Mureinik Oct 20 '21 at 18:51
  • 4
    Use: `print(str(n)[::-1])` – Tim Biegeleisen Oct 20 '21 at 18:52
  • I do not know what code to write – meti Oct 20 '21 at 18:53
  • 2
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 20 '21 at 18:55
  • 2
    So a Python tutorial is the first place to start. – enzo Oct 20 '21 at 18:55
  • Welcome to Stack Overflow! Please read [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822/4518341) We expect you to at least try writing something yourself first. For more tips, see [ask]. – wjandrea Oct 20 '21 at 18:56
  • 1
    Note that `12.789` is a [float](https://docs.python.org/3/library/functions.html#float), not a [decimal](https://docs.python.org/3/library/decimal.html). – wjandrea Oct 20 '21 at 19:06

1 Answers1

3

Break the problem up into its necessary steps, then figure out each one, and then combine all the steps at the end.

  1. Convert n to a string (see here for 10 examples of how to do this)
  2. Reverse the string (see here for plenty of examples)
  3. Turn the reversed string back into a float (see here for lots of good examples on how)

An example (there are many ways to do it though):

n = 12.345
n_string = str(n)
n_string_reversed = ''.join(reversed(n_string)) 
reversed_n = float(n_string_reversed)

Output of print(reversed_n):

543.21

Or, you could do all the steps on one line, but it's harder to read that way - you should generally go for readability over compactness, since code's main purpose is for humans to read, not just machines. If this were production code, it would need a big comment block explaining everything, but breaking it up into steps makes it obvious what's going on:

reversed_n = float(''.join(reversed(str(n))))

There are many other ways to accomplish this. The main goal of my answer is to encourage you to break up the problem into steps, and then figure out each one, rather than trying to go straight to the end result. Think about how you'd do the problem on paper, then figure out how to do each of those steps in code. I didn't know how to solve the problem, but I broke it up into steps, googled each of those steps, found the articles I linked, and then combined that knowledge to provide my answer.

Random Davis
  • 6,662
  • 4
  • 14
  • 24