from typing import Optional


def plot_number_formatter(val: float, _: Optional[float], precision: int = 3) -> str:
    """
    Format numbers in the plot.

    Parameters
    ----------
    val : float
        The value.
    _ : [None | float]
        The position (needed as input from FuncFormatter).
    precision : int
        Precision of the tick

    Returns
    -------
    tick_string : str
        The string to use for the tick
    """
    tick_string = f"${val:.{precision}g}"
    check_for_period = False
    # Special case if 0.000x or 0.00x
    if "0.000" in tick_string:
        check_for_period = True
        tick_string = tick_string.replace("0.000", "")
        if tick_string[1] == "-":
            tick_string = f"{tick_string[0:3]}.{tick_string[3:]}e-03"
        else:
            tick_string = f"{tick_string[0:2]}.{tick_string[2:]}e-03"
    elif "0.00" in tick_string:
        check_for_period = True
        tick_string = tick_string.replace("0.00", "")
        if tick_string[1] == "-":
            tick_string = f"{tick_string[0:3]}.{tick_string[3:]}e-02"
        else:
            tick_string = f"{tick_string[0:2]}.{tick_string[2:]}e-02"
    if check_for_period:
        # The last character before e-0x should not be a period
        if len(tick_string) > 5 and tick_string[-5] == ".":
            tick_string = tick_string.replace(".", "")
    if "e+" in tick_string:
        tick_string = tick_string.replace("e+0", r"\cdot 10^{")
        tick_string = tick_string.replace("e+", r"\cdot 10^{")
        tick_string += "}$"
    elif "e-" in tick_string:
        tick_string = tick_string.replace("e-0", r"\cdot 10^{-")
        tick_string = tick_string.replace("e-", r"\cdot 10^{-")
        tick_string += "}$"
    else:
        tick_string += "$"

    return tick_string