Easiest Way to Truncate Float to 2 Decimal Places

How to round to 2 decimals with Python?

You can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.

In your case, it would be:

answer = str(round(answer, 2))

How to truncate float values?

First, the function, for those who just want some copy-and-paste code:

def truncate(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '{}'.format(f)
if 'e' in s or 'E' in s:
return '{0:.{1}f}'.format(f, n)
i, p, d = s.partition('.')
return '.'.join([i, (d+'0'*n)[:n]])

This is valid in Python 2.7 and 3.1+. For older versions, it's not possible to get the same "intelligent rounding" effect (at least, not without a lot of complicated code), but rounding to 12 decimal places before truncation will work much of the time:

def truncate(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '%.12f' % f
i, p, d = s.partition('.')
return '.'.join([i, (d+'0'*n)[:n]])

Explanation

The core of the underlying method is to convert the value to a string at full precision and then just chop off everything beyond the desired number of characters. The latter step is easy; it can be done either with string manipulation

i, p, d = s.partition('.')
'.'.join([i, (d+'0'*n)[:n]])

or the decimal module

str(Decimal(s).quantize(Decimal((0, (1,), -n)), rounding=ROUND_DOWN))

The first step, converting to a string, is quite difficult because there are some pairs of floating point literals (i.e. what you write in the source code) which both produce the same binary representation and yet should be truncated differently. For example, consider 0.3 and 0.29999999999999998. If you write 0.3 in a Python program, the compiler encodes it using the IEEE floating-point format into the sequence of bits (assuming a 64-bit float)

0011111111010011001100110011001100110011001100110011001100110011

This is the closest value to 0.3 that can accurately be represented as an IEEE float. But if you write 0.29999999999999998 in a Python program, the compiler translates it into exactly the same value. In one case, you meant it to be truncated (to one digit) as 0.3, whereas in the other case you meant it to be truncated as 0.2, but Python can only give one answer. This is a fundamental limitation of Python, or indeed any programming language without lazy evaluation. The truncation function only has access to the binary value stored in the computer's memory, not the string you actually typed into the source code.1

If you decode the sequence of bits back into a decimal number, again using the IEEE 64-bit floating-point format, you get

0.2999999999999999888977697537484345957637...

so a naive implementation would come up with 0.2 even though that's probably not what you want. For more on floating-point representation error, see the Python tutorial.

It's very rare to be working with a floating-point value that is so close to a round number and yet is intentionally not equal to that round number. So when truncating, it probably makes sense to choose the "nicest" decimal representation out of all that could correspond to the value in memory. Python 2.7 and up (but not 3.0) includes a sophisticated algorithm to do just that, which we can access through the default string formatting operation.

'{}'.format(f)

The only caveat is that this acts like a g format specification, in the sense that it uses exponential notation (1.23e+4) if the number is large or small enough. So the method has to catch this case and handle it differently. There are a few cases where using an f format specification instead causes a problem, such as trying to truncate 3e-10 to 28 digits of precision (it produces 0.0000000002999999999999999980), and I'm not yet sure how best to handle those.

If you actually are working with floats that are very close to round numbers but intentionally not equal to them (like 0.29999999999999998 or 99.959999999999994), this will produce some false positives, i.e. it'll round numbers that you didn't want rounded. In that case the solution is to specify a fixed precision.

'{0:.{1}f}'.format(f, sys.float_info.dig + n + 2)

The number of digits of precision to use here doesn't really matter, it only needs to be large enough to ensure that any rounding performed in the string conversion doesn't "bump up" the value to its nice decimal representation. I think sys.float_info.dig + n + 2 may be enough in all cases, but if not that 2 might have to be increased, and it doesn't hurt to do so.

In earlier versions of Python (up to 2.6, or 3.0), the floating point number formatting was a lot more crude, and would regularly produce things like

>>> 1.1
1.1000000000000001

If this is your situation, if you do want to use "nice" decimal representations for truncation, all you can do (as far as I know) is pick some number of digits, less than the full precision representable by a float, and round the number to that many digits before truncating it. A typical choice is 12,

'%.12f' % f

but you can adjust this to suit the numbers you're using.


1Well... I lied. Technically, you can instruct Python to re-parse its own source code and extract the part corresponding to the first argument you pass to the truncation function. If that argument is a floating-point literal, you can just cut it off a certain number of places after the decimal point and return that. However this strategy doesn't work if the argument is a variable, which makes it fairly useless. The following is presented for entertainment value only:

def trunc_introspect(f, n):
'''Truncates/pads the float f to n decimal places by looking at the caller's source code'''
current_frame = None
caller_frame = None
s = inspect.stack()
try:
current_frame = s[0]
caller_frame = s[1]
gen = tokenize.tokenize(io.BytesIO(caller_frame[4][caller_frame[5]].encode('utf-8')).readline)
for token_type, token_string, _, _, _ in gen:
if token_type == tokenize.NAME and token_string == current_frame[3]:
next(gen) # left parenthesis
token_type, token_string, _, _, _ = next(gen) # float literal
if token_type == tokenize.NUMBER:
try:
cut_point = token_string.index('.') + n + 1
except ValueError: # no decimal in string
return token_string + '.' + '0' * n
else:
if len(token_string) < cut_point:
token_string += '0' * (cut_point - len(token_string))
return token_string[:cut_point]
else:
raise ValueError('Unable to find floating-point literal (this probably means you called {} with a variable)'.format(current_frame[3]))
break
finally:
del s, current_frame, caller_frame

Generalizing this to handle the case where you pass in a variable seems like a lost cause, since you'd have to trace backwards through the program's execution until you find the floating-point literal which gave the variable its value. If there even is one. Most variables will be initialized from user input or mathematical expressions, in which case the binary representation is all there is.

Easiest way to truncate float to 2 decimal places?

You cannot round a Float or Double to 2 decimal digits exactly.
The reason is that these data types use a binary floating point representation,
and cannot represent numbers like 0.1 or 0.01 exactly.
See for example

  • Why Are Floating Point Numbers Inaccurate?
  • What Every Computer Scientist Should Know About Floating-Point Arithmetic

But you said:

I need my return value to be in quarter steps (i.e. 6.50, 6.75, 5.25, etc),

and that is exactly possible because 0.25 = 2-2 can be represented exactly as a floating point number.

The round() function rounds a floating point number to the nearest integral value.
To round to the nearest quarter, you just have to "scale" the calculation with the factor 4:

func roundToNearestQuarter(num : Float) -> Float {
return round(num * 4.0)/4.0
}

roundToNearestQuarter(6.71) // 6.75
roundToNearestQuarter(6.6) // 6.5

Truncate float (not rounded) to 2 decimal places

This can be done by dropping the extra digits you don't want by using multiplication and division. For example, if you want 0.994 to be 0.99, you can multiply by 100 (to cover 2 decimal places), then truncate the number, and then divide it back by 100 to it to the original decimal place.

example:

  0.994 * 100 = 99.4
99.4 truncated = 99.0
99.0 / 100 = 0.99

So here is a function that will do that:

const truncateByDecimalPlace = (value, numDecimalPlaces) =>
Math.trunc(value * Math.pow(10, numDecimalPlaces)) / Math.pow(10, numDecimalPlaces)

console.log(truncateByDecimalPlace(0.996, 2)) // 0.99

Truncate number to two decimal places without rounding

Convert the number into a string, match the number up to the second decimal place:

function calc(theform) {    var num = theform.original.value, rounded = theform.rounded    var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]    rounded.value = with2Decimals}
<form onsubmit="return calc(this)">Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" /><br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly></form>

How to round each item in a list of floats to 2 decimal places?

"%.2f" does not return a clean float. It returns a string representing this float with two decimals.

my_list = [0.30000000000000004, 0.5, 0.20000000000000001]
my_formatted_list = [ '%.2f' % elem for elem in my_list ]

returns:

['0.30', '0.50', '0.20']

Also, don't call your variable list. This is a reserved word for list creation. Use some other name, for example my_list.

If you want to obtain [0.30, 0.5, 0.20] (or at least the floats that are the closest possible), you can try this:

my_rounded_list = [ round(elem, 2) for elem in my_list ]

returns:

[0.29999999999999999, 0.5, 0.20000000000000001]

JavaScript displaying a float to 2 decimal places

float_num.toFixed(2);

Note:toFixed() will round or pad with zeros if necessary to meet the specified length.

Round float to 2 decimal places in C language?

I agree with the other comments/answers that using floating point numbers for money is usually not a good idea, not all numbers can be stored exactly. Basically, when you use floating point numbers, you sacrifice exactness for being able to storage very large and very small numbers and being able to store decimals. You don't want to sacrifice exactness when dealing with real money, but I think this is a student project, and no actual money is being calculated, so I wrote the small program to show one way of doing this.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void)
{
double number, percent_interest, interest, result, rounded_result;

number = 123.8798831;
percent_interest = 0.1;
interest = (number * percent_interest)/100; //Calculate interest of interest_rate percent.
result = number + interest;
rounded_result = floor(result * 100) / 100;

printf("number=%f, percent_interest=%f, interest=%f, result=%f, rounded_result=%f\n", number, percent_interest, interest, result, rounded_result);

return EXIT_SUCCESS;
}

As you can see, I use double instead float, because double has more precession and floating point constants are of type double not float. The code in your question should give you a warning because in

float number = 123.8798831;

123.8798831 is of type double and has to be converted to float (possibly losing precession in the process).

You should also notice that my program calculates interest at .1% (like you say you want to do) unlike the code in your question which calculates interest at 10%. Your code multiplies by 0.1 which is 10/100 or 10%.



Related Topics



Leave a reply



Submit