Printing float objects

does anyone know how to print float objects within a string … i am trying to send a string to a function that will print and it is coming back as objecttype float 64 instead of printing the actual number … does anyone know why this is happening … it doesn’t happen with ints … this is an example
image

if you can post the text code of a complete, minimal example that might make it easier for people to duplicate what you’re seeing.
Also, the version of numba, python, and the operating system you’re using are all helpful. And the error you’re seeing.

@njit()
def make_msg():
var_1 = 5343.6165
var_2 = 1112
msg = (“hey this is a float”, var_1, “and this is an int”, var_2)
return msg

@njit()
def print_msg(msg: str):
print(msg)

make_msg()

numba==0.58.1
python 3.10.10
windows 10 pro

and it isn’t printing the float variable as the number … numba seems to not like to print floats … instead it prints the object type as you can see in the picture

Here is a gist which implements str() for floats.

It’s kind of silly that this isn’t fully implemented. I probably should have sent a PR long ago when the issue (and here) for this was first filed. Back then I offered the same solution. Trouble is it isn’t quite as fast as the native python implementation, but it works!

1 Like

Hey, @DannyWeitekamp,
Thank you for your Numba float-to-string conversion implementation.
Even if it is not as fast as Python’s native function it can still be useful i.e. if you simply need to print an error message.
Awesome!

@DannyWeitekamp hey thank you so much for this … but is there a way to control the amount of dec places that are shown … right now this is looking kinda nuts … i would like it to return the same amount of dec places as the original number no matter what float length i use

whenever you use just one floating point it is fine … but after you do .01 or more then it starts to go a little nuts lol

also it doesn’t seem to be useable when you aren’t using numba … is it possible to make it usable in regular python mode?

from nb_quantfreedom.nb_helper_funcs import nb_float_to_str

@njit()
def make_msg():
    var_1 = 5343.6165
    var_2 = 1112
    msg = "hey this is a float " + nb_float_to_str(var_1) + " and this is an int " + str(var_2)
    return msg


@njit()
def print_msg(msg: str):
    print(msg)


make_msg()
>>> 'hey this is a float 5343.6165000000000873 and this is an int 1112'
import numpy as np
import numba
from numba import types, njit
from numba.cpython.unicode import _empty_string, _set_code_point, PY_UNICODE_1BYTE_KIND
from numba.extending import overload_method

DIGITS_START = 48
DIGITS_END = 58
DASH = 45
DOT = 46
PLUS = 43
E_CHAR = 101

and then the rest is just your code for float to str

You might find printf() useful. It gives you the standard C format specifiers for width and decimal places.

I am not sure how this works … i followed what this guy did and i am getting nothing in return … am i doing something wrong?