0
public class Convert
{
    public void MMtofeetfraction(float millimeters)
    {
        if ((millimeters % 304.8f) != 0)
        {
            int feet = (int)(millimeters / 304.8f);
            double inchWithDecimal = millimeters * 0.03937;
            string s = inchWithDecimal.ToString("0.0000");
            string[] parts = s.Split('.');
            int i1 = int.Parse(parts[0]);
            float i2 = float.Parse("0." + parts[1]);
            int inch = i1 % 12;
            var accuracy = 16;
            double num = 1;
            double frac = i2 * accuracy;
            num = Math.Round(frac);
            if (num != 0)
            {
                while (num % 2 == 0)
                {
                    num = num / 2;
                    accuracy = accuracy / 2;
                }
                if (inch != 0)
                {
                    Debug.Log("Fraction output: " + feet + "'-" + inch + " " + num + "/" + accuracy + "\"");
                }
                else
                {
                    Debug.Log("Fraction output: " + feet + "'-" + num + "/" + accuracy + "\"");
                }
            }
            else
            {
                Debug.Log("Fraction output: " + feet + "'-" + inch + "\"");
            }
        }
        else
        {
            Debug.Log("Fraction output: " + Math.Round(millimeters / 304.8) + "'");
        }
    }
}
  • Input 1440 : output : 4' 7 1/2"
  • Input 1550 : output : 5' 1 "
  • Input 1530 : output : 5' 1/4"

Now, this code works and gives output as needed. I was looking to improvise this code by removing string splitting and other string formatting. Can someone help with inbuilt functions to handle this?

  • "I was looking to improvise this code" did you meant to say "improve" ? – Mong Zhu Jun 25 '21 at 08:06
  • You can easily split a number into its integral and fractional parts (as long as the number doesn't exceed 2^31) like so: Given `double value` which is non-negative and less than 2^31: `int intPart = (int)value; double fractPart = value - intPart;` – Matthew Watson Jun 25 '21 at 08:11
  • @MongZhu Yes I meant improve. Typo. – Bhupiister singh Jun 27 '21 at 21:23
  • @MatthewWatson Input to my function can be a negative number as we;. And would it be possible to have the number up to 4 decimal places like this "inchWithDecimal.ToString("0.0000" – Bhupiister singh Jun 27 '21 at 21:26

0 Answers0