General way to print floats without the .0 part

This works if your values are larger than 1:

from math import isinf

def float2str(value):
    if isinf(value):
        raise ValueError("value not finite")
    return str(value) if isinstance(value, int) else f'{value:.309g}'

You’re definitely going to run into rounding errors though.

In Chrome 124.0.6367.208 (Official Build) (64-bit) and Firefox 126.0 (64-bit), at least, this works

<svg xmlns="http://www.w3.org/2000/svg" width="400E+2" height="400E+2" viewBox="0 0 124 124" fill="none">
<circle cx="1.2109E+1" cy="7.5391E+1" r="1.1641E+1" fill="black"/>
</svg>

both with the E and with e.

1 Like

But note that this is available only for SVG attributes:
https://www.w3.org/TR/2011/REC-SVG11-20110816/types.html#DataTypeNumber

1 Like

Scientific notation is supported by Chromium and Firefox. And if I’m correct in thinking that this is the SVG standard: Basic Data Types and Interfaces – SVG 1.1 (Second Edition) then it should be supported by every browser/viewer.

But as it also states <number>'s are represented as “float, SVGNumber or a SVGAnimatedNumber” in SVG DOM [1], so floating point errors may still occur.

So I think that @MRAB’s first answer is the easiest and best solution for this. [2]


  1. SVGNumber is pretty much just another name for float, the same goes for SVGAnimatedNumber ↩︎

  2. Tho it’s not converted back into a number but at that point, it shouldn’t be necessary to have it as an int or float anymore just put it in ↩︎