Yoshi
Yoshi

Reputation: 15

Cannot return a float value of -1.00

I am currently doing an assignment for a computer science paper at university. I am in my first year.

in one of the questions, if the gender is incorrect the function is suppose to return a value of -1. But in the testing column, it says the expected value is -1.00. And I cannot seem to be able to return the value of '-1.00', it will always return a value of -1.0 (with one zero). I used the .format to make the value 2sf (so it will appear with two zero's) but when converting it to a float the value always returns "-1.0".

return float('{:.2f}'.format(-1))

Upvotes: 0

Views: 540

Answers (3)

miracle173
miracle173

Reputation: 1983

What does the following code do?

print(float('{:.2f}'.format(-1)))

The '{:.2f}'.format(-1) creates some string representation of -1. defined by the format string. The float(...) converts this string to the float 1. The print command converts this float to a sting, using some default format, and prints this string to the screen. I think that isn't what you expected because the format you used does not effect the print command in formatting the string. I assume you want

print('{:.2f}'.format(float(-1)))

and this actually does what you want, it prints

1.00

http://ideone.com/GyINQR

It is not necessary to convert -1 explicitely to float

print('{:.2f}'.format(-1))

gives the desired result:
http://ideone.com/U2RTMX

Upvotes: 0

Crabime
Crabime

Reputation: 684

I don't know exactly what you have done, but i had tried this way and output what you expect.

    b = -1    
    >>> print("%.2f" % (b))
    -1.00
    >>> print("%.2f" % (-1))
    -1.00

Upvotes: 0

Tom Zych
Tom Zych

Reputation: 13586

This isn’t as clear as it could be. Does your instructor or testing software expect a string '-1.00'? If so, just return that. Is a float type expected? Then return -1.0; the number of digits shown does not affect the value.

Upvotes: 1

Related Questions