Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm having trouble putting 3 values in line 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading