0

I am trying to calculate the square root of a number to where it looks like this:

Enter number for square root: 2
---------------------------------
.41

However, with the current code I have:

def calc(self, event=None):
    try:
        self.result_var.set("The square root of %s is %0.2f" % \
            (self.number.get(), sqrt(float(self.number.get()))) )

I get 1.41.

How do I remove the "1" so it only displays ".41?"

4
  • 1
    cast to int and subtract? num - int(num) , just like all the oldsckool cool c kids. Commented May 23, 2013 at 4:32
  • 2
    The square root of 2 isn't 0.41. Your current code is right. If you want to remove the integer part, you can do n % 1. Commented May 23, 2013 at 4:37
  • @Blender, I know, however I need it to display only the decimal places. To be more correct, I'll edit my print to "The approximate decimal square root is" Commented May 23, 2013 at 4:38
  • @Blender -- Note that % 1 doesn't give the decimal part for negative numbers. That's not a concern if you're getting the number from a square root, but ... in general I suppose it could be. Commented May 23, 2013 at 4:51

1 Answer 1

4

You can use divmod to split a number into it's integer part and decimal part:

>>> divmod(1.41,1)
(1.0, 0.4099999999999999)

so,

intpart,decimalpart = divmod(number,1)

I suppose to get this to work for negative numbers, you'd need something like:

_,decimalpart = divmod(abs(number),1)

or more succinctly:

decimalpart = abs(number) % 1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.