How to do Number.toFixed

782 views
Skip to first unread message

Tarler

unread,
Nov 11, 2013, 7:43:23 AM11/11/13
to haxe...@googlegroups.com
Hello,

Is there a best way to get Number.toFixed using Haxe? I can't find it in anywhere in the existing core API

Suggestions like the following, to multiply and divide by a precision factor, do not work for all numbers

 var input:String = "2495.70";
 
var parsed:Float = Std.parseFloat(input);
 trace
("parsed:" + parsed);//2495.7
 
var product:Float = parsed * 100;//do something with our float
 trace
("product:" + product);//249569.99999999997, would expect 249570
 
var prec = 100;
 trace
("rounded:" + Std.int(product*prec) / prec );//249569.99


To get around this, I am just getting access to the "native" toFixed method in a roundabout way, but this will surely break on targets other than Flash and Javascript

 public static function toFixed(x:Float, decimalPlaces:Int):String {
 
var f = Reflect.field(x, "toFixed");
 
return Reflect.callMethod(x, f, [decimalPlaces]);
 
}

Any ideas appreciated.

Thanks,
James

Justin L Mills

unread,
Nov 12, 2013, 1:58:28 PM11/12/13
to haxe...@googlegroups.com
Polygonal has sprintf functionality
http://lab.polygonal.de/?p=1939
--
To post to this group haxe...@googlegroups.com
http://groups.google.com/group/haxelang?hl=en
---
You received this message because you are subscribed to the Google Groups "Haxe" group.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages