How to format numbers without rounding in Python? - python

I was searching online but could find if this is posible. I have a number, let say 1234.5963657 and I know that with f-string I can do this f"{number:,.2f}" to obtain 1,234.60.
The thing is that the number has been rounded, and I don't want that, I would like to obtain: 1,234.59. My question is if there's a way to do this as simple as the f-string.
If not, I would have to truncate it or do something like this:
number = 1234.5963657
int_part, dec_part = str(number).split('.')
new_number = f"{int_part}.{dec_part[:2]}" # 1234.59
Hope my question is clear. Thanks

Add one more digit of precision then use a slice to exclude the unwanted digit.
f"{number:,.3f}"[:-1]

Related

Remove decimals from a Float column

shocked beyond belief how difficult this is turning out to be. All I can find are suggestions to change the format of the column to 'int' but I need to keep the comma thousand separators and changing the format to int gets rid of them. THEN i can't find anything on how to add comma separators to an int column. any ideas? really is nothing for me to share in addition to above in terms of what i've tried.
Format your floats...in a string format?
my_string = '{:,.0f}'. format(my_number)
E.g.:
x = 1000.00
'{:,.0f}'. format(x)-> 1,000
Which gives you what you want...something you can print with commas. 0f sets to 0 precision. (for how many decimal places)

Display a specific digit within a string

What is the best way to display a specific decimal place in a string. So 23.54 and print only 4. Right now I'm doing this but it dont seem very effective.
money=input("how much money")
totalmoney=(float(money))
totalmoney1=(float("{:.1f}".format(totalmoney)))
totalmoney2=(float("{:.2f}".format(totalmoney)))
totalmoney3 =(round(totalmoney2 - totalmoney1,2))
totalmoney4=(abs(totalmoney3))
print(totalmoney4*100, "cents")
You can just split the String at the decimal and then access whatever decimal place you want.
For example, -1 can be used to access the last Decimal place.
money = input('How much Money: ')
cents = money.split('.')[-1] if '.' in money else 0
print(cents[-1])
(Note: This code sample will not work as expected if there is no decimal place given.)
I think this is what you want...
print(input('How much money? ').split('.')[-1]['your-index-goes-here'])
# this code will still work if there's no decimal point
For eg.
print(str(23.54).split('.')[-1][2]) # returns '4'
Tell me if there's any errors...
if I'd understood your question correctly, you want the second digit after floating point. I guess you could use something like
str(round(totalmoney,2))[-1]
please let me know if it helped.
you multiply a string by 10 and print it, you'll see 10 strings.

Strict Python formatting for floats

I'm using PYTHON to write to a file where the formatting is very strict. I have 10 available spaces in each column which cannot be exceeded.
I want to write the as many decimals as I can, but if the number is negative, the minus sign must be preferred over the last decimals. Also the period in the float must be counted into the number of available spaces. Numbers should be right trunctated
Example:
Let's say I want to print two numbers
a = 123.4567891011
b = 0.9876543210
Then I would want the result:
123.4567890.98765432
But if I now have the following:
a = -123.1111111111
b = 98765.432101234
c = 567
d = 0.1234
Then I'd want:
-123.1111198765.4321 567.0 0.1234
Would be to nice use exponential notation for high numbers, but not a necessity. I'm unable to find the answer. All I can find is to fix the format to number of significant digits, which really won't help me.
I've tried several methods of the
f.write({0:>10}{1:>10}.format(a,b))
but can't figure it out. Hope you see what I`m looking for.
Okay, so I found a way. I basically convert everything to strings and use:
f.write("{0:>10.10}{1:>10.10}".format(str(a),str(b)))
and so on..

Best way to add a "+" and "-"?

What is the best way to display either a + in front, for a float? Lets say if a user inputs the number "10". I want to have a "+" appear in front of it since it is a positive number. If it were a negative number then I would leave it as it is.
Would I have to use an if statement and then convert it to a string and then add in the + sign? Or is there an easier way?
Use the format() function:
>>> format(10, '+f')
'+10.000000'
>>> format(-10, '+f')
'-10.000000'
>>> format(3.14159, '+.3f')
'+3.142'
See the Format Specification Mini-Language for the specific formatting options; prepending a number format with + makes it include a plus for positive numbers, - for negative. The last example formats the number to use 3 decimals, for example.
If you need to remove the negative sign, you'd have to do so explicitly using .lstrip():
>>> format(10, '+f').lstrip('-')
'+10.000000'
>>> format(-10, '+f').lstrip('-')
'10.000000'
but that'd be quite confusing a specification to read, in my opinion. :-)
Use formatting - and then remove any leading - from the result:
print format(10, '+').lstrip('-')
The first thing I thought:
userInput=int(input("Enter number: "))
if userInput > 0:
print ("+"+userInput)
else:
pass
Formatting is just the way to go though, faster and cleaner.

python string formatting fixed width

I want to put a bunch of floating point numbers into a fixed-width table. That is, I want a maximum of 12 characters used. I want a minimum of 10 decimals used (if available); however, if 10 decimals makes it take up more than 12 characters, then round. My original thought was to try something like this
# I only want 12 characters used total
num1 = 0.04154721841
num2 = 10.04154721841
# not what I want
print "{:<12.11g}".format((num1))
# what I want
print "{:<12.10f}".format((num1))
# not what I want
print "{:<12.10f}".format((num2))
# what I want
print "{:<12.11g}".format((num2))
There has to be a way to achieve this without writing a function to check every number and give formatting based on the above conditions. What am I missing?
I'm not sure this is what you are looking for, since it's not accomplished entirely with the format string, however, you could just use string slicing to lop-off the trailing chars when things get too long:
num1 = 0.04154721841
num2 = 10.04154721841
num3 = 1002.04154721841
print "{0:<12.11g}".format(num1)[:12]
print "{0:<12.11g}".format(num2)[:12]
print "{0:<12.11g}".format(num3)[:12]
outputs:
0.0415472184
10.041547218
1002.0415472
Beyond that, I'd say you should just write a function, though I'm not an expert on the str.format stuff, so I may be missing something.

Categories

Resources