Skip to content

Instantly share code, notes, and snippets.

@gavinking
Last active October 5, 2015 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavinking/49d3e906ae724a0352bf to your computer and use it in GitHub Desktop.
Save gavinking/49d3e906ae724a0352bf to your computer and use it in GitHub Desktop.
format a floating point number
shared String formatFloat(
"The floating point value to format."
Float float,
"The minimum number of allowed decimal places.
If `minDecimalPlaces<=0`, the result may have no
decimal point."
Integer minDecimalPlaces=1,
"The maximum number of allowed decimal places.
If `maxDecimalPlaces<=0`, the result always has no
decimal point."
Integer maxDecimalPlaces=9) {
variable {Character*} digits = {};
variable Integer i = maxDecimalPlaces;
Float m = float.magnitude;
while (true) {
Float f = m * 10.0.powerOfInteger(--i); //really slow!!
Float d = (f.fractionalPart * 10).wholePart;
Character c = (d.integer+'0'.integer).character;
digits = digits.follow(c);
if (f.wholePart==0.0) {
break;
}
}
String string = String(digits);
Integer point = string.size - maxDecimalPlaces;
String wholePart;
String fractionalPart;
if (point>0) {
wholePart = string[0:point];
fractionalPart = string[point...];
}
else {
wholePart = "0";
fractionalPart
= string.padLeading(maxDecimalPlaces, '0');
}
String normalized =
fractionalPart
.trimTrailing('0'.equals)
.padTrailing(minDecimalPlaces, '0');
String signed =
float.negative
then "-" + wholePart
else wholePart;
return normalized.empty
then signed
else signed + "." + normalized;
}
module web_ide_script "1.0.0" {
// Add module imports here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment