how to round a float to 2 DP

i have found functions that truncate the decimal places to create an integer.

but i have the time in seconds and wish to have a set amount of decimal places say 3.

thanks

edit: in C# please

1 Like

8 Answers

8

If it's just for changing to string:

yourFloat.ToString("F2")

If you want the float itself truncated:

yourFloat = Mathf.Round(yourFloat * 100f) / 100f;

I had no idea about yourFloat.ToString("F2"). Always used your second solution. Thanks for sharing.

–

To get time in thousandths of a second, you could do this (C# syntax) ...

float seconds = Time.time;
int thousandths = (int)(seconds * 1000.0f);

The C# system library includes Math.Round, which lets you pass in the number of decimal places you want to preserve. However it works with double and decimal numbers, which may not be desirable. Unity's Mathf.Round does not let you specify decimal places (feature request??), but you can implement your own version like this:

public static float Round(float value, int digits)
{
    float mult = Mathf.pow(10.0f, (float)digits);
    return Mathf.Round(value * mult) / mult;
}

Note that it will be more efficient to just perform the computation inline with your code, knowing the appropriate power of 10, for example:

float rounded = Mathf.Round(seconds * 1000.0f) / 1000.0f;

or (if you don't care about rounding):

float rounded = (int)(seconds * 1000.0f) / 1000.0f;

Finally, if this is just for formatting and display, not calculation, then there are several alternatives shown in this question.

It is Mathf.Pow not Mathf.pow, just in case you get an error.

–

//create a double
//create a float
float a;
double b;
b = System.Math.Round(a,2);
// replace number 2 with number of decimals you wish to round upto.

By far the simplest solution, System.Math.Round(a,2); Question, will this allow the file size to be smaller, or is it the same as "using System;" namespace? In other words, will this only extract the math.round method from system without importing all the other methods?

–

just add this at the top:

using System;

It will give you access to math.round

Then do something cool like this:

speedCapped = (float)Math.Round((double)lerpedSpeed,2);

Its a little over the top but cool.

using UnityEngine.SceneManagement; SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex); This is the correct way because this method takes "int" type parameter and you have to sure one thing that your all scenes have been added in build Settings.

–

i foudn this example in the end on stackoverflow.:

decimal a = 1.994444M;

Math.Round(a, 2); //returns 1.99

decimal b = 1.995555M;

Math.Round(b, 2); //returns 2.00

i think this is a little neater than yours Mike, cheers for the reply tho.

bah math isnt there and its not an overloaded function of mathf

–

see my updated answer for an implementation of Round.

–

Just include System instead

–

Thanks. You forgot a SceneManager. though. SceneManager.LoadScene (SceneManager.GetActiveScene ().name);

–

I know this is an old question, but since it’s the top Google result I wanted to update it a bit.


I was having problems with rounding when it came to when the latest to-round-digit was a 5. It sometimes (but not with every value!) did not round up, but down.

For instance, if I’m rounding to 1 decimal:

float rounded = Math.Round(1.45f, 1);
# rounded = 1.5

Which is correct and what I wanted.

However:

float rounded = Math.Round(1.55f, 1);
# rounded = 1.5

Is not correct…! This has to do with the MidpointRounding enum value, and needing to cast a float to a decimal.


I wrote an extension method, which seems to solve the issues, based on Stackoverflow user RahulTripathi’s comment and docs

  /// <summary>
  /// This rounds a float to specified decimals.
  /// It solves issues when rounding some .5 values.
  /// </summary>
  /// <param name="originalValue"></param>
  /// <param name="decimals"></param>
  /// <returns></returns>
  public static float RoundCorrectly(this float originalValue, int decimals)
  {
       decimal originalAsDecimal = (decimal) originalValue; // Float needs to be cast to decimal. 
       const MidpointRounding midwayRounding = MidpointRounding.AwayFromZero;

       var rounded = (float) Math.Round(originalAsDecimal, decimals, midwayRounding);
       return rounded;
  }

try these …

decimal d = 100.123456M;

decimal dc = Math.Round(d, 2);
d.ToString(“#.##”);
String.Format(“{0:0.00}”, d);

More info…Round a decimal value to 2 decimal places

Dov

I know this is an old post, but I simply useMathf.Ceil(myVariable * 10) / 10 //add a '0' to each 10 to increase the decimal places

It’s simple and it works.