Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FR] Round with decimals #1

Open
thareh opened this issue May 7, 2023 · 1 comment
Open

[FR] Round with decimals #1

thareh opened this issue May 7, 2023 · 1 comment

Comments

@thareh
Copy link

thareh commented May 7, 2023

Previous FR here: brl.mod #226

Nice to see a math category!

Perhaps round with decimal precision and a round function that returns a string with the unnecessary bits removed from the end would be a good fit in here somewhere? (math.round or similar?)

I came up with the following solution, but I guess it'd be better to use snprintf directly instead of using TStringBuilder or perhaps there's another even better solution altogether - but here goes:

Private
Global sb:TStringBuilder = New TStringBuilder()

Public

Rem
bbdoc: 
EndRem
Function RoundToString:String(val:Double, decimals:Int)
	sb.SetLength(0)
	sb.FormatDouble("%." + decimals + "f", val)
	Return sb.ToString()
EndFunction

Rem
bbdoc:
EndRem
Function Round:Double(val:Double, decimals:Int)
	Return Double(RoundToString(val, decimals))
EndFunction

Rem
bbdoc:
EndRem
Function RoundToString:String(val:Double, decimals:Int, pretty:Int)
	Local str:String = RoundToString(val, decimals)
	
	If Not pretty
		Return str
	EndIf
	
	For Local i:Int = str.length-1 To 0 Step -1
		If str[i] = 48
			Continue
		EndIf
		
		If str[i] = 46
			Return str[..i]
		EndIf
		
		Return str[..i+1]
	Next
EndFunction

Thanks and a have pleasant day!

@thareh
Copy link
Author

thareh commented May 7, 2023

Sidenote:
I'm using sb.SetLength(0) to clear the string builder, perhaps a dedicated Clear() method would be a good addition to TStringBuilder as well?

Thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant