Solved Reading proper decimal values on lower numbers?

Hi,

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

Hi,

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,
        0.00018878623163019122,
        1.1076812650509394e-03,
        1.3882258325566638e-06]

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]

Cheers
zipit

MAXON SDK Specialist
developers.maxon.net

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.

Hello,

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 :)

Cheers,
Manuel

MAXON SDK Specialist

MAXON Registered Developer