Z
Z
Zefirot2021-11-10 21:55:25
C++ / C#
Zefirot, 2021-11-10 21:55:25

What is the best way to round a float?

I know the topic is hackneyed, but where I don’t look at the solution and everywhere the solution goes by turning it into a decimal and then into a float, as a result, I get these two methods, one float rounds, the other string float rounds, that is, methods return from float or string rounded float

public float FloatRoundFromFloat(float f){
  decimal d = (decimal)Math.Round(f, 4); f = (float)d;
  return f;
  }
public float FloatRoundFromString(string s){
  decimal d = Math.Round(Convert.ToDecimal(s.Replace(',', '.')), 4);
  float f = (float)d;
  return f;
  }

Are these the maximum solutions? Are these methods correct, or what would you advise better, the fact is that I have a lot where they are used, I would like these methods to be the most productive ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2021-11-10
@Zefirot

Why use decimal is not clear
Return a float to get what, instead of 0.0004 = 0.0003999999?

K
K1ald, 2021-11-11
@K1ald

My "rounding code" from a Unity project (example):

public float countdown = 60;

        if (countdown > 0)
        {
            countdown -= Time.deltaTime;
            timerText.text = countdown.ToString();
            timerText.text = Mathf.Round(countdown).ToString();
        }

The code is responsible for reporting the time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question