Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Bug How to add all values from a Text array to a float variable

Discussion in 'Scripting' started by stoupas, Sep 12, 2023.

  1. stoupas

    stoupas

    Joined:
    Aug 26, 2021
    Posts:
    15
    So I have a Text[] and a float and I was wondering how I can add each of Text values to float and then set the text to that.
    Code (CSharp):
    1. public class TotalMoney : MonoBehaviour
    2. {
    3.     public Text textt;
    4.     public Text[] moneyFields;
    5.     public float totalMoney;
    6.  
    7.     void Update()
    8.     {
    9.         textt.text = "Total: " + totalMoney;
    10.     }
    11. }
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,833
    The concept is very simple:

    * iterate (loop) over the array
    * each Text in the array has a .text which is a string
    * convert the string to a float
    * add the float to a running total

    Code (CSharp):
    1. totalMoney = 0f;
    2. foreach (Text field in moneyFields)
    3. {
    4.     string displayed = field.text;
    5.     float amount = float.Parse(displayed);
    6.     totalMoney += amount;
    7. }
    There are gotchas, though.

    * what if the string doesn't convert to a float, because of punctuation or it's empty?
    * what if your user supplied strings like "€34,12" because that's how their country does it?
    * how do you deal with rounding errors or unexpectedly huge or tiny values?

    Using strings as a way of storing and working with numbers is a bad approach. You should be holding an array of floats, and converting them to strings for display purposes only.
     
    Last edited: Sep 12, 2023
  3. stoupas

    stoupas

    Joined:
    Aug 26, 2021
    Posts:
    15
    what do I put on strFloatValue?
     
  4. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,833
    Sorry, quick mistake there. I meant
    displayed
    .
     
  5. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,833
    Please use code tags. Maybe ChatGPT can be taught how to add [CODE] tags around forum posts.
     
    ijmmai likes this.