Python обрезать число до точки

Обрезать до трех знаков после запятой в Python

Используйте вокруг него float() , если хотите сохранить его как число с плавающей точкой.

Я думаю, что лучший и правильный способ — использовать модуль decimal .

import decimal a = 1324343032.324325235 decimal_val = decimal.Decimal(str(a)).quantize( decimal.Decimal('.001'), rounding=decimal.ROUND_DOWN ) float_val = float(decimal_val) print(decimal_val) >>>1324343032.324 print(float_val) >>>1324343032.324 

Вы можете использовать разные значения для rounding=decimal.ROUND_DOWN , доступны следующие опции: ROUND_CEILING , ROUND_DOWN , ROUND_FLOOR , ROUND_HALF_DOWN , ROUND_HALF_EVEN , ROUND_HALF_UP , ROUND_UP и ROUND_05UP . Вы можете найти объяснение каждой опции здесь, в документации.

Я нашел другое решение (оно должно быть более эффективным, чем обходные пути «колдовства»):

>>> import decimal # By default rounding setting in python is decimal.ROUND_HALF_EVEN >>> decimal.getcontext().rounding = decimal.ROUND_DOWN >>> c = decimal.Decimal(34.1499123) # By default it should return 34.15 due to '99' after '34.14' >>> round(c,2) Decimal('34.14') >>> float(round(c,2)) 34.14 >>> print(round(c,2)) 34.14 

Вы можете использовать следующую функцию для усечения числа до заданного числа десятичных знаков:

import math def truncate(number, digits) -> float: stepper = 10.0 ** digits return math.trunc(stepper * number) / stepper 
>> truncate(1324343032.324325235, 3) >> 1324343032.324 

Хорошо, это просто еще один подход, чтобы решить эту проблему, работая с числом как строкой и выполняя простой его фрагмент. Это дает вам усеченный вывод числа вместо округленного.

num = str(1324343032.324325235) i = num.index(".") truncated = num[:i+4] print(truncated) 

Конечно, тогда вы можете разобрать:

Читайте также:  Php class data types

Вы также можете использовать:

import math nValeur = format(float(input('Quelle valeur ? ')), '.3f') 

В Python 3.6 это будет работать.

a = 1.0123456789 dec = 3 # keep this many decimals p = 10 # raise 10 to this power a * 10 ** p // 10 ** (p - dec) / 10 ** dec >>> 1.012 

Это нормально только в этом конкретном случае.

Просто немного измените номер:

Дает вам 1324343032,325

def trun_n_d(n,d): s=repr(n).split('.') if (len(s)==1): return int(s[0]) return float(s[0]+'.'+s[1][:d]) 

Еще один вариант для trun_n_d :

def trun_n_d(n,d): dp = repr(n).find('.') #dot position if dp == -1: return int(n) return float(repr(n)[:dp+d+1]) 

Еще один вариант ( oneliner ) для trun_n_d [this, предполагает, что n ‘является str и’ d ‘является int ]:

def trun_n_d(n,d): return ( n if not n.find('.')+1 else n[:n.find('.')+d+1] ) 

trun_n_d дает желаемый результат как в Python 2.7, так и в Python 3.6

trun_n_d (1324343032.324325235,3) возвращает 1324343032.324

Аналогично, trun_n_d (1324343032.324 7 25235,3) возвращает 1324343032.324 .

Примечание 1 . В Python 3.6 (и, возможно, в Python 3.x) что-то вроде этого работает просто отлично:

def trun_n_d(n,d): return int(n*10**d)/10**d 

Но, таким образом, призрак закругления всегда скрывается вокруг.

Примечание 2 . В подобных ситуациях из-за внутренних чисел python , таких как округление и отсутствие точности, работа с n в качестве str намного лучше, чем его аналог int ; вы всегда можете привести свой номер к float в конце.

>>> float(1324343032.324325235) * float(1000) / float(1000) 1324343032.3243253 >>> round(float(1324343032.324325235) * float(1000) / float(1000), 3) 1324343032.324 

Я считаю, что использование функции format — плохая идея. Пожалуйста, смотрите ниже. Это округляет значение. Я использую Python 3.6.

Вместо этого используйте регулярное выражение:

>>> re.match(r'\d+.\d', str(1.999999)).group(0) '1.999' 

Используйте десятичный модуль. Но если вам нужно использовать числа с плавающей запятой и все же каким-то образом привести их к заданному количеству десятичных знаков, преобразование в строку со спиной обеспечивает (довольно неуклюжий, я боюсь) способ сделать это.

>>> q = 1324343032.324325235 * 1000 / 1000 >>> a = "%.3f" % q >>> a '1324343032.324' >>> b = float(a) >>> b 1324343032.324 

После поиска способа решения этой проблемы, без загрузки какого-либо модуля Python 3 или дополнительных математических операций, я решил проблему, используя только str.format () e .float (). Я думаю, что этот способ быстрее, чем использование других математических операций, как в большинстве обычных решений. Мне нужно было быстрое решение, потому что я работаю с очень очень большим набором данных, и поэтому он работает очень хорошо здесь.

def truncate_number(f_number, n_decimals): strFormNum = "" trunc_num = float(strFormNum.format(f_number)[:-5]) return(trunc_num) # Testing the 'trunc_num()' function test_num = 1150/252 [(idx, truncate_number(test_num, idx)) for idx in range(0, 20)] 

Возвращает следующий вывод:

[(0, 4.0), (1, 4.5), (2, 4.56), (3, 4.563), (4, 4.5634), (5, 4.56349), (6, 4.563492), (7, 4.563492), (8, 4.56349206), (9, 4.563492063), (10, 4.5634920634), (11, 4.56349206349), (12, 4.563492063492), (13, 4.563492063492), (14, 4.56349206349206), (15, 4.563492063492063), (16, 4.563492063492063), (17, 4.563492063492063), (18, 4.563492063492063), (19, 4.563492063492063)] 

Источник

Python: Truncate a Float (6 Different Ways)

Python Truncate Float Cover Image

In this tutorial, you’ll learn how to use Python to truncate a float, to either no decimal places or a certain number of decimal places. You’ll learn how to do this using the built-in int() function, the math library, and string methods, including Python f-strings. You’ll also learn how to truncate a list of floats.

Being able to truncate values in Python has a number of important benefits, such as being able to output numbers in a more presentation-ready format. Being able to output values in a more reader friendly format is an important skill to learn in order to make your data easier to look at.

The Quick Answer: Use math.trunc()

Quick Answer - Python Truncate Float

Use the int Function to Truncate a Float in Python

The built-in int() function takes a float and converts it to an integer, thereby truncating a float value by removing its decimal places.

The int() function works differently than the round() and floor() function (which you can learn more about here). The function only removes anything following the decimal, regardless of what follows it. This is differently than the round() function, as it does not round up. It’s also different from the floor() , which returns an integer now greater than a number.

Let’s see how we can use the int() function to truncate a float in Python:

# Truncate a float in Python with int() float1 = 123.356 float2 = -2434.545 print(int(float1)) print(int(float2)) # Returns: # 123 # -2434

We can see here that anything following the decimal place is truncated.

In the next section, you’ll learn how to use the math library to truncate a float in Python.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Use the Math Library to Truncate a Float in Python

Similar to the int() function, the math library has a library that can be helpful to truncate a float in Python, the trunc() function.

While it may seem trivial to use another library to do this, it can help your code read a little clearer to explain what the function is doing and why it’s doing it.

Because our intention is to truncate a float, the trunc() function makes this explicitly clear, whereas the int() function doesn’t.

Let’s see how we can use the trunc() function to truncate some numbers in Python:

# Truncate a float in Python with math.trun() import math float1 = 123.356 float2 = -2434.545 print(math.trunc(float1)) print(math.trunc(float2)) # Returns: # 123 # -2434

We can see here that the same result is returned as when using the int() function.

In the next section, you’ll learn how to use string methods to truncate a float in Python.

Want to learn more about calculating the square root in Python? Check out my tutorial here, which will teach you different ways of calculating the square root, both without Python functions and with the help of functions.

Use String Methods to Truncate a Float in Python

We can also use string methods to truncate a float in Python. This works by first converting a float to string and then manipulating the string.

Using the str.split() method, we can split a string at a period and keep only the first section of the split. You can learn more about splitting strings in this tutorial.

Let’s see how we can truncate a float in Python by using the str.split() method.

# Truncate a float in Python with str.split() float1 = 123.356 float2 = -2434.545 print(str(float1).split('.')[0]) print(str(float2).split('.')[0]) # Returns: # 123 # -2434
  1. We first convert the float to a string
  2. We then split the string using the . character
  3. Finally, we return the first item returned (the piece preceding the decimal)

In the next section, you’ll learn how to use f-strings to truncate a float in Python.

Want to learn more about calculating the square root in Python? Check out my tutorial here, which will teach you different ways of calculating the square root, both without Python functions and with the help of functions.

Use f-strings to Truncate a Float in Python

There may be times that you want to truncate a float to a certain number of decimal points. This can be helpful, say, when displaying currencies or percentages.

For this, we can easily use string formatting by way of the helpful f-string features in Python. With this, we can specify the number of decimal points to keep and convert the string back to a float.

# Truncate a float in Python with f-strings float1 = 123.356 float2 = -2434.545 # Keep two decimal places print(float(f'')) print(float(f'')) # Returns: # 123.36 # -2434.55

We can see here that we first convert the float to a string, returning only a certain number of decimal places. We then convert the string back to a float, using the float() function.

Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!

Truncate a List of Floats in Python Using a For Loop

There may be times when you are given a list of floats and need truncate all of them. One of the ways in which you can do this is by using a Python for loop.

When doing this, we can loop over each item in the list, truncate it, and add it to a new list.

Let’s see what this looks like in Python:

# Truncate a list of floats using a for loop floats = [1.234, 45.543, 132.87, 76.989] truncated = list() for float in floats: truncated.append(int(float)) print(truncated) # Returns: [1, 45, 132, 76]
  1. Instantiated a new, empty list to hold our truncate values
  2. Looped over each item in our list of floats and truncated it using the int() function
  3. Appended the truncated item to our list

We can also use a list comprehension to make this process a little bit easier, saving us the step of instantiating a new list first.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Truncate a List of Floats in Python Using a List Comprehension

The above section showed how to use a Python for loop to truncate a list of floats. We can also use a Python list comprehension to do this, thereby saving us some visual clutter and the need to instantiate an empty list first.

Let’s see how we can use a list comprehension to accomplish this:

# Truncate a list of floats using a list comprehension floats = [1.234, 45.543, 132.87, 76.989] truncated = [int(item) for item in floats] print(truncated) # Returns: [1, 45, 132, 76]

To learn more about Python list comprehensions, check out the image below that shows how they work:

Python List Comprehensions Syntax

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Conclusion

In this tutorial, you learned how to use Python to truncate a float. You learned how to do this using the int() function, the math library, and string methods. You also learned how to use for loops and list comprehensions to truncate a list of floating point values in Python.

To learn more about the math.trunc() function, check out the official documentation here.

Источник

Оцените статью