Command opposite to FormatAsFraction

Command opposite to FormatAsFraction

Maxim-CADman77
Advisor Advisor
521 Views
5 Replies
Message 1 of 6

Command opposite to FormatAsFraction

Maxim-CADman77
Advisor
Advisor

I'd like to know the most reliable way to get number (double) from a string.

I used to  use CDblAny but nowadays I got error because user's input was fractional "1/20" (which is valid yet not foreseen by me).

I see there is FormatAsFraction in iLogic ... maybe there is some "opposite" operator as well?

Thanks in advance.

Please vote for Inventor-Idea Text Search within Option Names

0 Likes
Accepted solutions (1)
522 Views
5 Replies
Replies (5)
Message 2 of 6

tdant
Collaborator
Collaborator

It's a much more difficult trick for computers to convert strings to numbers than the inverse. I think you'll have a much better time using a While loop to restrict the user's input to decimal only. Something like:

 

Dim val As Object = InputBox("Enter a decimal value")
Do While Not IsNumeric(val)
    MsgBox ("Invalid entry, please try again")
    val = InputBox("Enter a decimal value")
Loop
Dim formatVal As Double = CDbl(val)
 
0 Likes
Message 3 of 6

Maxim-CADman77
Advisor
Advisor

Input restriction is not applicable in my case.

Please vote for Inventor-Idea Text Search within Option Names

0 Likes
Message 4 of 6

Maxim-CADman77
Advisor
Advisor

I've found some C# sample - https://stackoverflow.com/questions/13903621/convert-a-text-fraction-to-a-decimal but I need it in iLogic and don't know how to convert the code.

Please vote for Inventor-Idea Text Search within Option Names

0 Likes
Message 5 of 6

tdant
Collaborator
Collaborator

I'm C# illiterate, but from what I can tell, that can be written in VB. Is there any chance you can use VBA instead of iLogic? If so, you can rope in Excel functionality to convert string fractions to decimals pretty easily.

0 Likes
Message 6 of 6

tdant
Collaborator
Collaborator
Accepted solution

It isn't pretty, but here's an iLogic function that will convert a fractional number to decimal:

 

Function ConvertFraction(inputString As String) As Double
	Dim splitResult() As String = inputString.Split(" ")
	Dim fractionResult() As String = splitResult(UBound(splitResult)).Split("/")
	
	Dim whole As Integer = 0
	If splitResult.Length > 1 Then
		whole = CInt(splitResult(LBound(splitResult)))
	End If
	
	Dim denominator As Integer = CInt(fractionResult(UBound(fractionResult)))
	Dim numerator As Integer = CInt(fractionResult(LBound(fractionResult)))
	
	ConvertFraction = whole + (numerator / denominator)
End Function

It will convert strings like "1/2" and "1 7/16", but not "1 / 2" or "1-7/16".