StrG (a bit like StrD)

Share your advanced PureBasic knowledge/code with the community.
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3870
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

StrG (a bit like StrD)

Post by wilbert »

There are serval posts on the forum on how to convert a float to exponential notation.
StrG is a sort of mix between StrD and exponential notation.
It takes the most appropriate approach based on the given precision.

Here's a little comparison

Code: Select all

;- Imports

CompilerIf #PB_Compiler_OS = #PB_OS_Linux
  Macro snprintf_name : "snprintf" : EndMacro
CompilerElse
  CompilerIf #PB_Compiler_OS = #PB_OS_Windows And #PB_Compiler_Processor = #PB_Processor_x86
    Macro snprintf_name : "__snprintf" : EndMacro  
  CompilerElse
    Macro snprintf_name : "_snprintf" : EndMacro
  CompilerEndIf  
CompilerEndIf

ImportC ""
  snprintf_d(*s, n, *fmt, precision, d.d) As snprintf_name
EndImport

;- StrE and StrG Procedures

Procedure.s StrE(Value.d, Precision = 10, Dot = '.')
  Protected.i i, n=Precision|1+10, f.q=$652a2e25; '%.*e'
  Protected Dim b.a(n)
  n = snprintf_d(@b(), n, @f, Precision, Value)-1
  For i=0 To n: If b(i)&-3=44: b(i)=Dot: Break: EndIf: Next
  ProcedureReturn PeekS(@b(), -1, #PB_Ascii)
EndProcedure

Procedure.s StrG(Value.d, Precision = 10, Dot = '.')
  Protected.i i, n=Precision|1+10, f.q=$672a2e25; '%.*g'
  Protected Dim b.a(n)
  n = snprintf_d(@b(), n, @f, Precision, Value)-1
  For i=0 To n: If b(i)&-3=44: b(i)=Dot: Break: EndIf: Next
  ProcedureReturn PeekS(@b(), -1, #PB_Ascii)
EndProcedure



Debug StrD(12000000)
Debug StrE(12000000)
Debug StrG(12000000)

Debug StrD(1.2345e80)
Debug StrE(1.2345e80)
Debug StrG(1.2345e80)
Windows (x64)
Raspberry Pi OS (Arm64)
User avatar
Kwai chang caine
Always Here
Always Here
Posts: 5342
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: StrG (a bit like StrD)

Post by Kwai chang caine »

Works very well, but like usually a little bit powerfull for me :mrgreen:
Thanks for sharing 8)
ImageThe happiness is a road...
Not a destination
Post Reply