Home > database >  I'm having trouble putting 3 values in line 16
I'm having trouble putting 3 values in line 16

Time:01-16

I need help converting the variable "r" to a float.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Calculate : MonoBehaviour
{
    double pi = 3.14159;
    public InputField r;
    public Text circumference;
    public Text area;

    public void calculate()
    {

        circumference.text = ("Circumference = "   2 * pi * r);
    }
}

I have tried using the TryParse method and Parse Method, They don't work or i'm not using them correctly. I left the code how I originally coded it.

If you can fix this please reply with an answer.

CodePudding user response:

float rF = float.Parse(r.text);

Remember about error handling, and making sure the input is always a float. Otherwise, use TryParse.

CodePudding user response:

What did happen when you used parse? This following example does what you want.

Note the CultureInfo.InvariantCulture in the conversion from and to string. It prevents conversion between . and , that could happen depending on your locale.

I'd recommend you use longer variable names for clarity in the future but of course that is up to you.

using System;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;

public class CalculateCircle : MonoBehaviour
{
    private double pi = 3.14159;
    public InputField r;
    public Text circumference;
    public Text area;

    private void Start()
    {
        r.onEndEdit.AddListener(delegate { Calculate(); });
    }

    public void Calculate()
    {
        float radius = 0;
        try
        {
            radius = float.Parse(r.text);
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }

        double circumferenceValue = 2 * pi * radius;
        double areaValue = pi * radius * radius;
        circumference.text = circumferenceValue.ToString(CultureInfo.InvariantCulture);
        area.text = areaValue.ToString(CultureInfo.InvariantCulture);
    }
}
  • Related