Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
Go Back  Xtreme Visual Basic Talk > > > Help converting decimals to fractions in a large program...


Reply
 
Thread Tools Display Modes
  #1  
Old 02-18-2008, 06:48 PM
BedRock's Avatar
BedRock BedRock is offline
Regular
 
Join Date: Dec 2006
Posts: 62
Unhappy Help converting decimals to fractions in a large program...


many of you know that I have been working on a program that has to do with designing cabinet doors based on user input, this program is working fairly well.

I have made a program that now takes care of converting decimals to fractions, but need to know how to incoorporate this program into my cabinet door program...

I think I need to assign at each entry box a single rename of each entry and send that to my Sub? or Function? called Dec2Frac...

But this is something I am very new at and everything I try to do when searching for help in help files seems to fail...

Any help from some of you Gurus would be most appreciated.

Here's where I need to start:

I have an input text box for length and width:

1) is it possible to enter simply a fraction to begin with in these boxes, instead of a decimal number?

2) after processing these numbers through the program, I need the answers to be displayed as fractions, and not decimals.

ex.: 21.813" should read as 21 13/16"

My Dec2Frac can accomplish this, but I need to format the number sent to the Dec2Frac Sub/Function (don't know which I should use) to be only the
.813 portion for the program to convert.

Is there a way to format the number before sending it to the Dec2Frac part of the program so it only receives the decimal portion of the number, and then return and post the fraction with the whole number in the text box???

I would sincerely appreciate any and all help, suggestion, etc..
Reply With Quote
  #2  
Old 02-18-2008, 07:33 PM
Gruff's Avatar
GruffHelp converting decimals to fractions in a large program... Gruff is offline
Bald Mountain Survivor

Retired Moderator
* Expert *
 
Join Date: Aug 2003
Location: Oregon, USA - deceased
Posts: 6,440
Default

Hi Rock,

It all depends on what you are doing with your input.
If you need to do math with your input then I would guess you would want to convert any input in your textbox into a floating point datatype. Probably a 'Double' data type. Once you have completed your calculations convert it back to a 'String' data type (text) for displaying purposes.

Sounds like you only need help with the input.

You could write your own function to convert fractional text into a numerical value or you could use the Dot Net equivalent of the MS Script Control.

The nice thing about the control is that does more than fractions. Any simple mathimatical equation can be converted from string input to numerical. That is the route I would follow.

....

Ah well I couldn't find the Dot.NET equivalent but you can still use the old com Script Control reference and its 'Eval()' Method. The method takes a string as input and outputs your double.

The following will take either a decimal number or a mixed number fraction as input.

Code:
Public Class Form1 'Add this to your project references first' Dim SC As MSScriptControl.ScriptControl Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load SC = New MSScriptControl.ScriptControl SC.Language = "VBScript" End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sPreview As String Dim Answer As Double sPreview = TextBox1.Text 'Replace the space with a Plus character sPreview = sPreview.Replace(" ", "+") Answer = SC.Eval(sPreview) MessageBox.Show(Answer) End Sub End Class
~T
__________________
Burn the land and boil the sea
You can't take the sky from me


~T

Last edited by Gruff; 02-18-2008 at 08:02 PM.
Reply With Quote
  #3  
Old 02-19-2008, 03:33 PM
BedRock's Avatar
BedRock BedRock is offline
Regular
 
Join Date: Dec 2006
Posts: 62
Default

Here's the delima I am in...

I have 11 output boxes that shows deminsions of different pieces of these doors that need to be converted into fraction form from decimal form. So I would assume a function is what I need in my program...

Where I seem to be stuck is in how to rename each textbox.text string into a value for the function to be able to process it as say Val(Input) and return it as textbox.text string to the appropriate box in my program gui. Would I do it before it comes to each step of processing the numerical data as a string in the textbox? In other words:

It has the input of always a width and height.

From there it goes through several steps, but before posting to the boxes on the gui, each numerical answer must be sent to:

Function Dec2Frac()

Say, Var(Input = 18.375)

'this needs to be formatted and rounded to where only the decimal part
'is used in the function like so:

Format Var(Input, ".###"), so that all that is processed is .375.

'Then each formatted Var(Input) is ran through my Dec2Frac Function converter code, and finally returned to the appropriate TextBox.Text, which is assigned "Output".

End Format

I hope you understand what I am trying to do here, I can explain it, make it work in a simple standalone program that only deals with decimal input numbers, but not with numbers containing whole numbers, as it returns fractions such as 40/32 for 1.25.....

Is there a sample program out there where two or more numerical answers are returned as strings in a fraction format such as TextBox.Text.ToString & Val(Output) = Format(TextBox.Text, ".###") as string
TextBox.Text = Val(Output)
Output = TextBox.Text

End Function

Then you would have to return to where the program sent the number to the Function and reintegrate with the whole number it was formatted away from.

I guess the line would look something like this?

TextBox.Text = CSng(TextBox.Text.ToString) & (Output.Text).ToString

I am not sure of the coding there...
Reply With Quote
  #4  
Old 02-19-2008, 06:28 PM
Gruff's Avatar
GruffHelp converting decimals to fractions in a large program... Gruff is offline
Bald Mountain Survivor

Retired Moderator
* Expert *
 
Join Date: Aug 2003
Location: Oregon, USA - deceased
Posts: 6,440
Default

Honestly I am very confused about what you want.

What datatype does your Dec2Frac function input argument take?
Can you post the source code?

Are you saying you do not know how to use the Dec2Frac function with your textboxes?

The following assumes you have one textbox for input and another for output
and that your Dec2Frac function is a function and not a sub-routine.
Code:
' If Dec2Frac takes a double variable for input then: txtOutput.text = Dec2Frac(Cdbl(txtInput.text)) ' If Dec2Frac takes a string variable for input then: txtOutput.text = Dec2Frac(txtInput.text)

Does this help?
~T
__________________
Burn the land and boil the sea
You can't take the sky from me


~T

Last edited by Gruff; 02-20-2008 at 09:16 AM.
Reply With Quote
  #5  
Old 02-20-2008, 09:52 AM
BedRock's Avatar
BedRock BedRock is offline
Regular
 
Join Date: Dec 2006
Posts: 62
Default

All decimal places are carried out to the thousandths...
and then the .xxx are converted to 32nds of an inch.

I suppose it would have be taken in as a Double... Since most all numbers are like the following in format:

32.5

before parsing.

Then I assume I would send them to Dec2Frac for processing into fraction form?

But... how do I keep from getting a fraction that includes the whole number of 32 included with the .5 in the parsed answer, by using the split command?

or can I format the number in some way to just use the .5 in the formula to return 1/2 and then join it back with the 32 and Output it in the desired TextBox as 32 1/2"??
Reply With Quote
  #6  
Old 02-20-2008, 10:18 AM
BedRock's Avatar
BedRock BedRock is offline
Regular
 
Join Date: Dec 2006
Posts: 62
Default

Maybe I didn't explain myself clear enough at the outset:

I wrote a program about a year ago to figure pieces for raised panel cabinet doors.

This program has two boxes that the user must input value into;

tbOpeningHeight.Text and tbOpeningWidth.Text

In order for the program to work, the user must enter a fractional amout in decimal form, so if a measurement for the OpeningHeight is 35 3/4 one must enter 35.75, and for OpenWidth a decimal equivalent must be entered for the fraction as well.

Then the user clicks on several options they can choose from:

what type of door, what type of pattern, what type of top rail, etc.

for each choice there is a sub routine after the main sub is ran that carries out different math processess to determine size, shape, etc. for each piece of lumber for that door or doors.

Besides the main sub, each extra sub returns numerical values displayed in whole.decimal values.

What I hope to do is run each whole.decimal number through the Dec2Frac Function to return a whole.fraction number and then return it as a text.string to it's appropriate textbox.

I have a small program that I wrote that I can input say .813 in one box and in the output box it will return 13/16. I need help in intergrating this Dec2Frac in my main program as a function Dec2Frac to deal with the decimal part of my answers but I have not reached that level of expertise as of yet...(:

I hope I have not been repetitive, but more concise as to what I am trying to do.

Thanks for any and all help you can and aleady have offered.
Reply With Quote
  #7  
Old 02-20-2008, 10:41 AM
AtmaWeapon's Avatar
AtmaWeaponHelp converting decimals to fractions in a large program... AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

I really fail to see the problem.

You want a method that can take a number as a parameter and return a string fractional representation. You wrote the method. Now you are confused when you get to the "copy the code from the test application into the new application" part?

My guess is that you actually mean "I found an application that does this on the internet, how do I get the source code of that application?"

Or is it that the real question is something different, and the answer has been slow in coming since it's been clouded by pages of irrelevant information?

I found something in your original post that seems unanswered, is this the real question?
"I have a number, say 10.813. I have a function that can tell me the fractional value of a number, so long as the whole part is zero. For example, 0.5 will return "1/2", but I cannot pass "1.5" as the number to this function. How do I remove the whole part of the number?"

If that's the question, we can come up with a reasonably reliable answer, so long as you don't mind using Decimal instead of Double as a data type. To get 0.5 from 8.5, we can subtract 8. To get 0.813 from 10.813, we subtract 10. We can deduce that, in general, to get the fractional part of x we must subtract the integral part of x from itself. The Math.Truncate function returns the integral part of a number. Given this, we can get the fractional part of any number via this process:
Code:
x = x - Math.Truncate(x)
Now, you can do this with Doubles and you might not have problems, but there are minor issues with representation that might cause problems. I'd use Decimal for anything where the decimal values are important, as it can theoretically support 28 decimal places with precision. The following application demonstrates a scenario where Double makes a mistake, but Decimal is OK:
Code:
Module Module1

    Sub Main()
        TestDouble()
        TestDecimal()
    End Sub

    Sub TestDouble()
        Dim full As Double = 1.09
        Dim chopped As Double = (full - Math.Truncate(full))
        Console.WriteLine(chopped.ToString())
    End Sub

    Sub TestDecimal()
        Dim full As Decimal = 1.09D
        Dim chopped As Decimal = (full - Math.Truncate(full))
        Console.WriteLine(chopped.ToString())
    End Sub

End Module
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #8  
Old 02-20-2008, 10:59 AM
BedRock's Avatar
BedRock BedRock is offline
Regular
 
Join Date: Dec 2006
Posts: 62
Default

Hello Atma,

I am somewhat insulted by your suggesting that i "found my Dec2Frac program on the internet". No, Atma, I did not find it on the internet.
I wrote the program myself, thank you. And I will post it here for proof, as you can probably tell from the coding, which is rather elementary, (because I do have other things to do during the day, but I like to learn new things in my spare time, one of them programming) that I did indeed write it myself.

I am not a copier of code as some are on this and many other sites, don't confuse me with those of that ilk please. I am here to get a hand up, not a hand out.


Private Function Dec2Frac()

Dim tbInput As Double
Dim Output As String
Dim d As Double
Dim numerator As Integer
Dim numerator1 As Double

Decimal.TryParse(tbInput.ToString, d.ToString)
d = (tbInput).ToString
numerator = CInt(d * 32)

'FRACTION REDUCTION...
If numerator = 2 Or 4 Or 6 Or 8 Or 10 Or 12 Or 14 Or 16 Or 18 Or 20 Or 22 Or 24 Or 26 Or 28 Or 30 Or 32 = True Then
If numerator = 2 Or 4 Or 6 Or 8 Or 10 Or 12 Or 14 Or 16 Or 18 Or 20 Or 22 Or 24 Or 26 Or 28 Or 30 Or 32 = False Then
Output = numerator.ToString & "/32"""
End If
'16's of an inch...
If numerator = 2 Then
numerator1 = numerator / 2
Output = numerator1.ToString & "/16"""
ElseIf numerator = 6 Then
numerator1 = numerator / 2
Output = numerator1.ToString & "/16"""
ElseIf numerator = 10 Then
numerator1 = numerator / 2
Output = numerator1.ToString & "/16"""
ElseIf numerator = 14 Then
numerator1 = numerator / 2
Output = numerator1.ToString & "/16"""
ElseIf numerator = 18 Then
numerator1 = numerator / 2
Output = numerator1.ToString & "/16"""
ElseIf numerator = 22 Then
numerator1 = numerator / 2
Output = numerator1.ToString & "/16"""
ElseIf numerator = 26 Then
numerator1 = numerator / 2
Output = numerator1.ToString & "/16"""
ElseIf numerator = 30 Then
numerator1 = numerator / 2
Output = numerator1.ToString & "/16"""
'8th's of an inch...
ElseIf numerator = 4 Then
numerator1 = numerator / 4
Output = numerator1.ToString & "/8"""
ElseIf numerator = 12 Then
numerator1 = numerator / 4
Output = numerator1.ToString & "/8"""
ElseIf numerator = 20 Then
numerator1 = numerator / 4
Output = numerator1.ToString & "/8"""
ElseIf numerator = 28 Then
numerator1 = numerator / 4
Output = numerator1.ToString & "/8"""
'4th's of an inch...
ElseIf numerator = 8 Then
numerator1 = numerator / 8
Output = numerator1.ToString & "/4"""
ElseIf numerator = 24 Then
numerator1 = numerator / 8
Output = numerator1.ToString & "/4"""
'halves on an inch...
ElseIf numerator = 16 Then
numerator1 = numerator / 16
Output = numerator1.ToString & "/2"""
ElseIf numerator = 32 Then
numerator1 = numerator / 32
Output = numerator1.ToString & """"
End If
End If

End Function

Reply With Quote
  #9  
Old 02-20-2008, 11:53 AM
Gruff's Avatar
GruffHelp converting decimals to fractions in a large program... Gruff is offline
Bald Mountain Survivor

Retired Moderator
* Expert *
 
Join Date: Aug 2003
Location: Oregon, USA - deceased
Posts: 6,440
Default

BedRock,

I am sure AtmaWeapon reply was not meant to insult. He like myself have been attempting to understand what the heck you want. I think that if you re-read your posts you will see that you have not boiled it down to something we can answer. This means we have to guess. Which is a waste of our time.

After looking at your code I see that your level is novice. Not a problem. We all have to start somewhere.

1) I see no input or output for your function.
There are two types of modular procedures in VB.
'Sub Routines' and 'Functions'.

Both are used when code needs to be repeated and to reduce program complexity.

Both can take arguments which are passed into them.

Functions are different from Sub-Routines in that they are meant to return a single value as output. The function name itself represents the output value.

The format of a function roughly is:

<Scope> Function <FunctionName> (Arguments) AS <DataType>

For example:
Code:
Private Function Dec2Frac(Byval DecValue as double) as string Dim Frac as string ' Convert Dec to Frac Here. Return Frac ' <--- This puts the string value of Frac into Dec2Frac when it is called. End Function

In use you would call your function from someplace else as follows.

Code:
Dim DecVal as double DecValue = 2.125 TextBox1.text = Dec2Frac(DecVal)
__________________
Burn the land and boil the sea
You can't take the sky from me


~T
Reply With Quote
  #10  
Old 02-20-2008, 12:00 PM
AtmaWeapon's Avatar
AtmaWeaponHelp converting decimals to fractions in a large program... AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

AGH Gruff posted while I was still typing! I'm going to add some analysis to the suggestions.

I didn't mean to offend, it just seemed odd that you claimed to have something that worked but wanted us to make another one.

There's some fairly serious errors in the function from what I see; I'm not certain you've tested all values against it. For example, let's consider these two If statements:
Code:
If numerator = 2 Or 4 Or 6 Or 8 Or 10 Or 12 Or 14 Or 16 Or 18 Or 20 Or 22 Or 24 Or 26 Or 28 Or 30 Or 32 = True Then
If numerator = 2 Or 4 Or 6 Or 8 Or 10 Or 12 Or 14 Or 16 Or 18 Or 20 Or 22 Or 24 Or 26 Or 28 Or 30 Or 32 = False Then
Sometimes it's helpful to expand an If statement to its full representation to understand why it's not doing what you want. Fully expanded, it's as if you wrote this:
Code:
If (numerator = 2) = True Or 4 = True Or ... 32 = True Then
numerator = 2 is a statement that evaluates to 2, which can be interpreted as true. There's no way to do a comparison against multiple values, you would have to rewrite it as something like this:
Code:
If numerator = 2 Or numerator = 4 Or numerator = 6...
It'd actually be more elegant to determine if the number is less than 32 and even:
Code:
If (numerator <= 32) AndAlso (numerator Mod 2 = 0) Then
Now we have a secondary problem: the second if statement falls within the first, and it is kind of contradictory. If I follow the logic as I believe you interpreted it, you accidentally wrote something that says:
Code:
If (numerator is an even number <= 32) Then
    If (numerator is an odd number or > 32) Then
        ...
There's likely a more elegant way to do this; my first thought is to simply make a table of the decimal values from 1/32 to 32, then do on-the-fly conversions. The basic idea would be to get a decimal value, find it in the lookup table, then convert x/32 to a fraction.

I swear there's a formulaic way to do this that I've forgotten, though. I'm going to chew on it for a bit before making a definitive answer.

This was a pretty useful link; I still think since we're only working with multiples of two up to 32 a table-based approach would be simpler. Still, kudos to that website describing the Euclidean theorem better than my Cryptography professor.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.

Last edited by AtmaWeapon; 02-20-2008 at 12:08 PM.
Reply With Quote
  #11  
Old 02-20-2008, 12:42 PM
Gruff's Avatar
GruffHelp converting decimals to fractions in a large program... Gruff is offline
Bald Mountain Survivor

Retired Moderator
* Expert *
 
Join Date: Aug 2003
Location: Oregon, USA - deceased
Posts: 6,440
Default

Hey Atma! I looked in the forum history but couldn't find the algorythm so I checked out my personal library and found something I put together a while back. It not only reduces but also has the advantage of rounding a decimal number to the nearest desired fraction. Handy if your user inputs .12 instead of .125

Code:
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim DecVal As Double Dim DecRounded As Double DecVal = 21.625 MessageBox.Show(Dec2Frac(DecVal, DecRounded)) End Sub Private Function Dec2Frac(ByVal fBaseNum As Double, ByRef AdjustedNumber As Double) As String 'Converts a Decimal value input into a string containing a Mixed Fraction Dim Numerator As Integer Dim Denominator As Integer Dim total As Double Dim DecWholeNo As Integer = 0 Dim DecFracNo As Double = 0 Dim sWhole As String = "" Dim sFrac As String = "" Denominator = 32 DecWholeNo = GetWholeNumber(fBaseNum) DecFracNo = GetDecFrac(fBaseNum) Do Until total >= (DecFracNo - ((1 / Denominator) / 2)) Numerator = Numerator + 1 total = Numerator / Denominator Loop AdjustedNumber = DecWholeNo + total Call ReduceFraction(Numerator, Denominator) If DecWholeNo > 0 Then sWhole = DecWholeNo.ToString & " " End If sFrac = Numerator & "/" & Denominator Return sWhole & " " & sFrac End Function Private Sub ReduceFraction(ByRef Numerator As Integer, ByRef Denominator As Integer) Dim Divisor As Integer Dim nCount As Integer nCount = 1 Divisor = 1 While nCount < Denominator If (Numerator Mod nCount) = 0 Then If (Denominator Mod nCount) = 0 Then Divisor = nCount End If End If nCount = nCount + 1 End While Numerator = Numerator / Divisor Denominator = Denominator / Divisor End Sub Private Function GetWholeNumber(ByVal fVal As Double) As Integer GetWholeNumber = Fix(fVal) End Function Private Function GetDecFrac(ByVal fVal As Double) As Double GetDecFrac = fVal - Fix(fVal) End Function End Class
__________________
Burn the land and boil the sea
You can't take the sky from me


~T
Reply With Quote
  #12  
Old 02-20-2008, 12:45 PM
BedRock's Avatar
BedRock BedRock is offline
Regular
 
Join Date: Dec 2006
Posts: 62
Default

I don't know what to post here to help yall understand what I need to do.

I can put it in words...uh, well maybe I can't, because I can't seem to explain to you all what I need done in my program, and that's probably my short coming in that I am not to well educated in VB.

Atma, please accept my apology if you didn't mean to come across as insulting, but I am at my wits end on trying to work with fractions in VB.

There is a lot of info in working with decimals, but very little in working with fractions, especially in the books I have read. And I find VB express's help section sometimes very hard to understand. This is a new area of VB for me, the coding that is.

The reason I used a Function instead of a Sub was that I thought a Function did a very straight forward task, for instance, taking in numbers, running them through a set code which never changes based on anything, except the numbers fed into it, and spitting out a result. Kind of like a mold in a stamp mill in an iron shop. You can change what material you put in, but the process is always the same, as is the outcome. Am I correct in that assumption?


I will post part of my original code that I need to pass to Dec2Frac before the final string is posted into the TextBox as a fraction...

Hint.. Some figure must be placed into the Height and width boxes before the program can begin processing anything, I may have to leave this as decimal figures, or have them parsed through Dec2Frac and reloaded as fractions when all selections are made and the whole program is ran?


Private Sub Main()
'BASIC CABINET CODE...(NO CENTER MULLS OR HORIZONTAL MULLS FIGURED IN)...

Dim OpeningHeight As Decimal
Double.TryParse(tbOpeningHeight.Text, OpeningHeight)
'Val(OpeningHeight.ToString)
OpeningHeight = tbOpeningHeight.Text - Math.Truncate(OpeningHeight)
Input = OpeningHeight
d = Input
Dec2Frac()

tbOpeningHeight.Text = Input
'Dec2Frac(tbInput).ToString()
'tbOpeningHeight.Text = Dec2Frac(CDbl(tbInput))
tbOpeningHeight.Text = OpeningHeight.ToString

Double.TryParse(tbOpeningWidth.Text, OpeningWidth)
tbOpeningWidth.Text = OpeningWidth.ToString


If OpeningHeight < 1 And OpeningWidth < 1 = True Then
Do
Loop Until OpeningHeight > 0 And OpeningWidth > 0 = True
ElseIf OpeningHeight > 1 And OpeningWidth > 1 = True Then
End If



Reply With Quote
  #13  
Old 02-20-2008, 12:54 PM
AtmaWeapon's Avatar
AtmaWeaponHelp converting decimals to fractions in a large program... AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Gruff's code covers more cases than mine; I only do n/32 where n is in the range 0..32.
Code:
Module Module1

    Private _lookup(32) As Decimal

    Sub Main()
        InitializeArray()

        Console.WriteLine("1/2: {0}", NumberToFraction(0.5D))
        Console.WriteLine("10 3/32: {0}", NumberToFraction(10.09375D))
        Console.WriteLine("5 5/16: {0}", NumberToFraction(5.3125D))
        Console.WriteLine("3 5/8: {0}", NumberToFraction(CDec(3D + (5D / 8D))))
    End Sub

    Sub InitializeArray()
        For i As Integer = 0 To 32
            _lookup(i) = CDec(i) / 32D
        Next
    End Sub

    Function NumberToFraction(ByVal input As Decimal) As String
        Dim output As String = ""

        ' strip any whole numbers
        Dim wholePart As Decimal = Math.Truncate(input)
        input -= wholePart

        ' Find the decimal in the array
        Dim numerator As Integer = Array.IndexOf(_lookup, input)
        Dim denominator As Integer = 32

        If numerator > 0 Then
            ' If the decimal value was found, our numerator is the index in the array;
            ' The fraction is now numerator/32.  Now we find the reduced fraction.
            While numerator Mod 2 = 0
                numerator \= 2
                denominator \= 2
            End While

            output = String.Format("{0} {1}/{2}", wholePart, numerator, denominator)
        Else
            ' The fraction is not in the lookup table; just return the value
            output = input.ToString()
        End If

        Return output
    End Function

End Module
Each has its virtues; both will work.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #14  
Old 02-20-2008, 01:00 PM
BedRock's Avatar
BedRock BedRock is offline
Regular
 
Join Date: Dec 2006
Posts: 62
Default

I understand how to make decimals into fractions...

What I do not understand is how to send the data from the text boxes to the function or sub that does the conversion and then back to the textbox as a string and post it in the box.

Especially since I have about 12 such boxes...

would I need to use an array and list each box within that array?
Or would I simply place a line of code before parsing what is entered into the box and send it to Dec2Frac and then join it back to the whole number after truncation, parse the number and send it to the textbox as a string?

That is where my major hangup us right now.

And again, thanks guys for you help.
Reply With Quote
  #15  
Old 02-20-2008, 01:05 PM
BedRock's Avatar
BedRock BedRock is offline
Regular
 
Join Date: Dec 2006
Posts: 62
Default

Atma and Gruff, if it would not be too much to ask, could you send me the code you posted with lines explaining what each line does according to how the code is written?

If it is too much trouble I understand. But I want to learn about the coding, what and why it does what it does, and any and all help is greatly appreciated.

My email address is

Edit:
Removed email address

Thank you very much.

Last edited by Gruff; 02-20-2008 at 06:47 PM.
Reply With Quote
  #16  
Old 02-20-2008, 01:35 PM
AtmaWeapon's Avatar
AtmaWeaponHelp converting decimals to fractions in a large program... AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

My comments are in the code. If you can't determine what a line like numerator \= 2 does with a little bit of research, you have more important problems to address than converting numbers from one format to another.

With respect to getting data from a text box into a function, that is entirely application-specific. Personally I hate using text boxes for numbers because it makes things more complicated, but I can post a naive explanation.

Suppose you have txtOne and txtTwo that are text box controls containing numeric values, and you want to add them together then display the result in txtThree as a fraction, using my NumberToFraction method. One way to do this is as follows
Code:
' Convert text values to Decimal values
Dim value1 as Decimal = Decimal.Parse(txtOne.Text)
Dim value2 as Decimal = Decimal.Parse(txtTwo.Text)
Dim total as Decimal = value1 + value2

txtThree.Text = FractionToNumber(total)
This would logically be called from some event, for example a button's click event.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #17  
Old 02-20-2008, 02:51 PM
BedRock's Avatar
BedRock BedRock is offline
Regular
 
Join Date: Dec 2006
Posts: 62
Default

If you can't determine what a line like numerator \= 2 does

No, I think I can handle that...

Personally I hate using text boxes for numbers because it makes things more complicated, but I can post a naive explanation.

Well, MY application calls for it, and I thought this was a place that beginners like myself could come and get help from those who were more educated on the matter.

1) You asked for a sample of my code: I posted it, and explained that I had the conversion of the decimal to fraction part solved.

2) I asked, as nice as I knew how, to please explain how one would get the data from the input box on a gui into the Function that I posted to convert decimals to fractions from the code of my first project that I have to enter data in in decimal format.

3) the answer that I got in post #16 does nothing more than add two decimal strings together and post them in a third answer box named textThree.Text

So I can either assume that my postings were never really looked at with a sincere desire to truly understand my predicament and help me solve the problem I needed help with, or this is not the website I originally thought it was when I signed on.

Could someone please tell me how writing a new decimal to fraction conversion program helps me in any way get the entered data into my already written (not copied) Function that is in my Program?

And how do these lines of code help me in any way deal with my situation?

Console.WriteLine("1/2: {0}", NumberToFraction(0.5D))
Console.WriteLine("10 3/32: {0}", NumberToFraction(10.09375D))
Console.WriteLine("5 5/16: {0}", NumberToFraction(5.3125D))
Console.WriteLine("3 5/8: {0}", NumberToFraction(CDec(3D + (5D / 8D))))


Perhaps I am having a bad day.

Or perhaps I do not know enough to be qualified to use this site?
Reply With Quote
  #18  
Old 02-20-2008, 03:08 PM
Gruff's Avatar
GruffHelp converting decimals to fractions in a large program... Gruff is offline
Bald Mountain Survivor

Retired Moderator
* Expert *
 
Join Date: Aug 2003
Location: Oregon, USA - deceased
Posts: 6,440
Default

Quote:
Originally Posted by BedRock View Post
I understand how to make decimals into fractions....
With due respect. Looking at your attempt at code I do not agree.

Quote:
Originally Posted by BedRock View Post
What I do not understand is how to send the data from the text boxes to the function or sub that does the conversion and then back to the textbox as a string and post it in the box.
Actually I have shown that in several of my earlier posts. See #4 and #9

Do you understand what 'Events' are?
You have to decide what event will trigger the actions you desire.
In other words what user action: keypress, button push, etc... will drive your code. This event will be where you put your code that:
1) Gathers all input textbox data
2) Makes your calculations
3) Posts your fractions to the relevant textboxes

If you want my honest opinion I think you are trying to sprint before you can crawl. You are missing some of the most fundemental concepts and language particulars.

I suggest you use the VB.NET tutorials. Doing the work as you go.
(My assumption is that you are using VB.NET 2005 or 2008 Express)

If you have questions on the tutorials and concepts we can help.

~T
__________________
Burn the land and boil the sea
You can't take the sky from me


~T
Reply With Quote
  #19  
Old 02-20-2008, 03:37 PM
BedRock's Avatar
BedRock BedRock is offline
Regular
 
Join Date: Dec 2006
Posts: 62
Default

Hi Gruff... sigh...

I know that my Dec2Frac is a bit archaic, but it works.

an event is triggered by a button press or similar event. Although I do not know how to use the RaiseEvent command yet.

But i feel like i have accomplished a great deal in just one year of learning VB.

My cabinet door program has 14 different options to choose from in door design, and each change recalculates the proportions of the different pieces of what goes into making up each door, so I guess you could say that is an event driven program.

The only reason I am having trouble with this is that it deals with something I can't find much info on, or something I seem to have a hard time understanding. The other came easy to me. I don't know why... but it did.

I did watch the tutorials as you suggested, but i am more of a hands on type person, I learn better by doing than by someone telling me how to do something.

I am sure that your dec2frac program is better written than mine, but mine has never returned an incorrect answer, and it always is in simplified form.

Thanks anyway for letting me vent...
And i am probably trying to sprint before i can crawl...
Reply With Quote
  #20  
Old 02-20-2008, 03:56 PM
AtmaWeapon's Avatar
AtmaWeaponHelp converting decimals to fractions in a large program... AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Quote:
Originally Posted by BedRock View Post
Well, MY application calls for it, and I thought this was a place that beginners like myself could come and get help from those who were more educated on the matter.
Over the years, I've seen the use of text boxes to get numeric input can cause me to write anything from a dozen to hundreds of extra lines of code, depending on the numeric format desired, how extensive the validation should be, if copy/paste is desired, etc. I've coached several members on the forums through using text boxes for numeric input, and it always involves a good bit of work. If you use NumericUpDown it takes 0 extra lines of code and does all of the work for you. I was trying to teach you a good habit. If your application literally requires a text box then I understand; I just figured I'd put the numeric control out there to ease your burden.

Quote:
1) You asked for a sample of my code: I posted it, and explained that I had the conversion of the decimal to fraction part solved.
I analyzed your code and pointed out why it's a bad idea.

These two lines don't even compile:
Code:
        Decimal.TryParse(tbInput.ToString, d.ToString)
        d = (tbInput).ToString
The first line is a syntax error; it passes a String as the second parameter rather than a double. The second line is trying to store a string value in a Double variable. How do you explain that the function was working when it doesn't even compile?

When I fix those errors, the output is (mostly) correct, so it's possible that you added the errors because you didn't know how to get the value from the text box. Still, your thread topic and recurring question is "How do I convert decimals to fractions?", when what you really want to ask is "How do I get data from a text box and use it in a function?"

Still, those If statements really don't do anything and are a very bad idea.

Quote:
2) I asked, as nice as I knew how, to please explain how one would get the data from the input box on a gui into the Function that I posted to convert decimals to fractions from the code of my first project that I have to enter data in in decimal format.

3) the answer that I got in post #16 does nothing more than add two decimal strings together and post them in a third answer box named textThree.Text
You asked "How do I get the data from a text box and use it in a function?"

My code takes data from two text boxes, converts them to numbers, and does some processing with them. I'm sorry I didn't write something that is exactly what you need, but I fail to understand how my example is useless to you.

Quote:
So I can either assume that my postings were never really looked at with a sincere desire to truly understand my predicament and help me solve the problem I needed help with, or this is not the website I originally thought it was when I signed on.

Could someone please tell me how writing a new decimal to fraction conversion program helps me in any way get the entered data into my already written (not copied) Function that is in my Program?
Your point is valid; we have spent a while discussing decimal to fraction conversion when your real question is about getting data from your user interface. This is some kind of communication breakdown and I apologize. Somewhere along the line I was missing this point.

Quote:
And how do these lines of code help me in any way deal with my situation?

Console.WriteLine("1/2: {0}", NumberToFraction(0.5D))
Console.WriteLine("10 3/32: {0}", NumberToFraction(10.09375D))
Console.WriteLine("5 5/16: {0}", NumberToFraction(5.3125D))
Console.WriteLine("3 5/8: {0}", NumberToFraction(CDec(3D + (5D / 8D))))


Perhaps I am having a bad day.

Or perhaps I do not know enough to be qualified to use this site?
It's generally bad practice to comment things that are obvious. I considered it an insult to your intelligence to be this verbose:

"0.5 is equal to 1/2, which is 16/32. When I pass 0.5 to NumberToFraction, I hope that "1/2" will be printed to the screen."

"10.09375 is equal to 10 3/32. When I pass..."

Now, I've done enough bickering in this post. Sometime this evening when I'm not so grumpy, I'm going to calmly and slowly explain how you get a numeric value from a text box and pass it to a function when the user clicks a button. I don't know what else to do, but I assure you my previous example would be useful if you sought to understand it.

Also, just to be spiteful, I'm going to show you how using a NumericEdit control will reduce the amount of code you need to write. When people quit using text boxes for numeric input, this forum's inbound posts will drop by a visible margin.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program... Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
 
Help converting decimals to fractions in a large program...
Help converting decimals to fractions in a large program...
 
-->