Hi nauna,
Refer below sample.
HTML
Percentage : <asp:TextBox runat="server" ID="txtPercentage" /><br />
<asp:Button ID="Button1" Text="Convert" runat="server" OnClick="ConvertData"/>
Code
C#
protected void ConvertData(object sender, EventArgs e)
{
double percentage = Convert.ToDouble(txtPercentage.Text);
double convertToDecimal = percentage / 100;
string fraction = DecimalToFraction(convertToDecimal);
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('" + fraction + "');", true);
}
public string DecimalToFraction(double value)
{
string result;
double numerator, realValue = value;
int num, den, decimals, length;
num = (int)value;
value = value - num;
value = Math.Round(value, 5);
length = value.ToString().Length;
decimals = length - 2;
numerator = value;
for (int i = 0; i < decimals; i++)
{
if (realValue < 1)
{
numerator = numerator * 10;
}
else
{
realValue = realValue * 10;
numerator = realValue;
}
}
den = length - 2;
string ten = "1";
for (int i = 0; i < den; i++)
{
ten = ten + "0";
}
den = int.Parse(ten);
num = (int)numerator;
result = SimplifiedFractions(num, den);
return result;
}
string SimplifiedFractions(int num, int den)
{
int remNum, remDen, counter;
if (num > den)
{
counter = den;
}
else
{
counter = num;
}
for (int i = 2; i <= counter; i++)
{
remNum = num % i;
if (remNum == 0)
{
remDen = den % i;
if (remDen == 0)
{
num = num / i;
den = den / i;
i--;
}
}
}
return num.ToString() + "/" + den.ToString();
}
VB.Net
Protected Sub ConvertData(ByVal sender As Object, ByVal e As EventArgs)
Dim percentage As Double = Convert.ToDouble(txtPercentage.Text)
Dim convertToDecimal As Double = percentage / 100
Dim fraction As String = DecimalToFraction(convertToDecimal)
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "Message", "alert('" & fraction & "');", True)
End Sub
Public Function DecimalToFraction(ByVal value As Double) As String
Dim result As String
Dim numerator As Double, realValue As Double = value
Dim num, den, decimals, length As Integer
num = CInt(value)
value = value - num
value = Math.Round(value, 5)
length = value.ToString().Length
decimals = length - 2
numerator = value
For i As Integer = 0 To decimals - 1
If realValue < 1 Then
numerator = numerator * 10
Else
realValue = realValue * 10
numerator = realValue
End If
Next
den = length - 2
Dim ten As String = "1"
For i As Integer = 0 To den - 1
ten = ten & "0"
Next
den = Integer.Parse(ten)
num = CInt(numerator)
result = SimplifiedFractions(num, den)
Return result
End Function
Private Function SimplifiedFractions(ByVal num As Integer, ByVal den As Integer) As String
Dim remNum, remDen, counter As Integer
If num > den Then
counter = den
Else
counter = num
End If
For i As Integer = 2 To counter
remNum = num Mod i
If remNum = 0 Then
remDen = den Mod i
If remDen = 0 Then
num = num / i
den = den / i
i -= 1
End If
End If
Next
Return num.ToString() & "/" & den.ToString()
End Function
Screenshot
For more acurate result refer below link.