Solved Reading proper decimal values on lower numbers?


I'm writing a script that exports the position of an object. In the process, I'm truncating them to only four decimals.
Wrote the a truncate function. It works but not on low numbers.

For example,

Actual Position: Vector(0, 139.213, 93.26)
X-Position: 2.42398958609e-05
Resulting truncation: 2.4239

It turns out the script reads the pseudo decimal to an actual decimal. Is there a way to read the numbers as this 0.0000242398958609 so the function works as expected or should I revise the function?

Here is the current code:

def truncate(num):
    num_str = str(num)
    num = num_str.split(".")
    num_real = num[0]
    num_dec  = num[1][:4]
    new_num_str = "{}.{}".format(num_real, num_dec)
    new_num = float(new_num_str)

    return new_num


that your script is not working has not anything to do with pseudo decimals, but the fact that you are treating numbers as strings (which is generally a bad idea) in a not very careful manner. When you truncate the string representation of a number which is represented in scientific notation (with an exponent), then you also truncate that exponent and therefor change the value of the number.

To truncate a float you can either take the floor of my_float * 10 ** digits and then divide by 10 ** digits again or use the keyword round.

data = [0.03659665587738824,

for n in data:
    rounded = round(n, 4)
    floored = int(n * 10000) / 10000
    print(n, rounded, floored)

0.03659665587738824 0.0366 0.0365
0.00018878623163019122 0.0002 0.0001
0.0011076812650509394 0.0011 0.0011
1.3882258325566637e-06 0.0 0.0
[Finished in 0.1s]


MAXON SDK Specialist

RE: treating numbers as strings (which is generally a bad idea) in a not very careful manner.
THanks for the reminder. I initially thought I could get away with such a rudimetary approach

RE: code
Interesting. Your algorithm is way more useful. Thanks for sharing.


Thanks again @zipit for the fast and nice reply :+1:

I also move this thread to general programming as it's not related to Cinema 4D :)


MAXON SDK Specialist

MAXON Registered Developer