Search code examples
floating-pointhaxe

How to reliably format a floating point number to a specified number of decimal places in Haxe


I was wondering if there is a reliable way to convert a Float x in haxe to a String with a specified number of decimal places, e.g. 3.

A straightforward method is to first convert x to a string representation, and then trim everything after a given number of characters after the decimal point ., as shown here. However, what happens if some platform shows a number like 0.0111 as 1.11e-2?

I can't seem to find a printf in haxe either, which would allow me to format the number the right way. I was wondering what's the best practice for doing this in haxe.

I wanted to obtain strings in the result, because in some systems, floating point numbers gives you, e.g., 0.19999.. from 2/10.0. And it would be inaccurate just to truncate certain number of characters after the decimal point.


Solution

  • public static function floatToStringPrecision(n:Float, prec:Int){
      n = Math.round(n * Math.pow(10, prec));
      var str = ''+n;
      var len = str.length;
      if(len <= prec){
        while(len < prec){
          str = '0'+str;
          len++;
        }
        return '0.'+str;
      }
      else{
        return str.substr(0, str.length-prec) + '.'+str.substr(str.length-prec);
      }
    }
    

    Round may fail on big numbers(> MAX_INT) on some platforms, so for that case you need your own round function.