Search code examples
javanumbersspecial-characterstostringinfinity

Using ∞ instead of "infinity" in toString()


How can I make Java use the ∞ symbol instead of the string "infinity" when printing/toString'ing floating-point values (float, double, Float, Double)?


Solution

  • You can't change the default toString method, which isn't for user display but for debug/logging.

    But you may configure your own DecimalFormat :

    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
    symbols.setInfinity("∞");
    DecimalFormat decimalFormat = new DecimalFormat("#.#####", symbols);
    

    You use it like this :

    String str = decimalFormat.format(myDouble);
    

    Note that the formater will automatically add a minus sign in case of negative infinity.