Last active
October 5, 2015 18:14
-
-
Save gavinking/49d3e906ae724a0352bf to your computer and use it in GitHub Desktop.
format a floating point number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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