January 23, 2021, 05:00:55 AM

Author Topic: [bb] TheCatWalksOnTheKeyboard-proof String-2-Float by CS_TBL [ 1+ years ago ]  (Read 562 times)

Offline BlitzBot

  • Jr. Member
  • **
  • Posts: 1
Title : TheCatWalksOnTheKeyboard-proof String-2-Float
Author : CS_TBL
Posted : 1+ years ago

Description : Handy for scriptparsers and other user input. Instead of bugging the user with error-popups when the input is unreadable, this routine tries to interprete the input and creates a nice new output.

"0.1.2.3" returns "12.3"
"-----5" returns "-5.0"
"1.024-.-5" returns "1024.5"
"1.000.000.00" returns "1000000.0"
"-1- 2 3 4 . 5 - 6" returns "-1234.56"

So, as you see: as a bonus we can now type "10.000.00" or "10 000" if we want tenthousand.

* Space are wiped-out.
* The most-right dot (if any) will be the decimal dot, the rest is ignored.
* The number of minus-chars defines whether it's a positive or negative value.


Code :
Code: BlitzBasic
  1. Function String2Float#(a$)
  2.         ;
  3.         ;       String2Float, by CS_TBL
  4.         ;
  5.         ;       allowed in the string are: dot, minus, space, 0123456789
  6.         ;       other chars before the 'value' return 0.0, and other things after the 'value' are ignored
  7.         ;
  8.         ;       examples:
  9.         ;
  10.         ;       "0.1.2.3" returns "12.3"
  11.         ;       "-----5" returns "-5.0"
  12.         ;       "1.024-.-5" returns "1024.5"
  13.         ;       "1.000.000.00" returns "1000000.0"
  14.         ;       "-1- 2 3 4 . 5 - 6" returns "-1234.56"
  15.         ;
  16.  
  17.         ; wipe spaces
  18.         a$=Replace$(a$," ","")
  19.  
  20.         If a$="" Return 0
  21.  
  22.         l=Len(a$)
  23.  
  24.         ; do we have an odd amount of '-' ?
  25.         az$=Replace$(a$,"-","")
  26.         m=l-Len(az$)
  27.  
  28.         ; yes? it's a negative number!
  29.         If m Mod 2 negative=True
  30.  
  31.         ; scan the value (without - ) for dots
  32.         For t=Len(az$)-1 To 0 Step -1
  33.                 If Not found
  34.                         If Mid$(az$,t+1,1)="."
  35.                                 found=True
  36.                                 foundpos=(Len(az$)-1)-t
  37.                         EndIf
  38.                 EndIf
  39.         Next
  40.         ; so we found the most-right dot, if any..
  41.  
  42.  
  43.         ; get rid of all the dots then
  44.         az$=Replace$(az$,".","")
  45.  
  46.         l=Len(az$)
  47.  
  48.         If found ; place 1 dot back
  49.                 az$=Left$(az$,l-foundpos)+"."+Right$(az$,foundpos)
  50.         EndIf
  51.  
  52.         If negative
  53.                 az$="-"+az$
  54.         EndIf
  55.  
  56.         Return Float(az$)
  57.        
  58. End Function


Comments : none...

 

SimplePortal 2.3.6 © 2008-2014, SimplePortal