Skip to content

Instantly share code, notes, and snippets.

@t-karcher
Last active October 4, 2023 13:42
Show Gist options
  • Save t-karcher/053b7097e744bc3ba4e1d20441ab72a7 to your computer and use it in GitHub Desktop.
Save t-karcher/053b7097e744bc3ba4e1d20441ab72a7 to your computer and use it in GitHub Desktop.
GDScipt function converting a floating point number to a string in scientific notation
func test_output():
print (get_scientific_notation(123456789.0, 0)) # 1e8
print (get_scientific_notation(123456789.0, 1)) # 1.2e8
print (get_scientific_notation(123456789.0)) # 1.2345678e8
print (get_scientific_notation(0.123456789, 0)) # 1e-1
print (get_scientific_notation(0.123456789, 1)) # 1.2e-1
print (get_scientific_notation(0.123456789)) # 1.2345678e-1
print (get_scientific_notation(12345, 0, true)) # 12e3
print (get_scientific_notation(1234567, 0, true)) # 1e6
print (get_scientific_notation(123456789, 0, true)) # 123e6
func get_scientific_notation(number: float, precision: int = 99, use_engineering_notation: bool = false) -> String:
var sign_ = sign(number)
number = abs(number)
if number < 1:
var exp_ = step_decimals(number)
if use_engineering_notation: exp_ = stepify(exp_ + 1, 3)
var coeff = sign_ * number * pow(10, exp_)
return String(stepify(coeff, pow(10, -precision))) + "e" + String(-exp_)
elif number >= 10:
var exp_ = String(number).split(".")[0].length() - 1
if use_engineering_notation: exp_ = stepify(exp_ - 1, 3)
var coeff = sign_ * number / pow(10, exp_)
return String(stepify(coeff, pow(10, -precision))) + "e" + String(exp_)
else:
return String(stepify(sign_ * number, pow(10, -precision))) + "e0"
@rdephillip
Copy link

For this to function in Godot 4 see updated code below:

func get_scientific_notation(number: float, precision: int = 99, use_engineering_notation: bool = false) -> String:
	var sign_ = sign(number)
	number = abs(number)
	if number < 1:
		var exp_ = step_decimals(number)
		if use_engineering_notation: exp_ = snapped(exp_ + 1, 3)
		var coeff = sign_ * number * pow(10, exp_)
		return str(snapped(coeff, pow(10, -precision))) + "e" + str(-exp_)
	elif number >= 10:
		var exp_ = str(number).split(".")[0].length() - 1
		if use_engineering_notation: exp_ = snapped(exp_ - 1, 3)
		var coeff = sign_ * number / pow(10, exp_)
		return str(snapped(coeff, pow(10, -precision))) + "e" + str(exp_)
	else:
		return str(snapped(sign_ * number, pow(10, -precision))) + "e0"

@t-karcher
Copy link
Author

Thanks! 👍 I hadn't even noticed yet that stepify has been renamed to snapped. I'll leave my code as it is, so whoever finds this page can choose between a working version for 3.x and 4.x. 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment