x


Changing float lenght

Hello,

I have float variables like 4.101814. How can I reduce its lenght to 2, so it would look like this: 4.10

Thanks!

more ▼

asked Aug 22 '11 at 03:33 PM

Dreeka gravatar image

Dreeka
129 50 62 65

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first
float val = 4.101814f;
float roundedVal = 0.01f * Mathf.Round(100.0f * val);
more ▼

answered Aug 22 '11 at 04:02 PM

sharat gravatar image

sharat
121 4 7 9

For efficiency you should use 100.0f but besides that absolutely right.

Oh for all Unityscript users that example is written in C# but the actual computation is the same:

// UnityScript
var val = 4.101814;
var roundedVal = 0.01 * Mathf.Round(100.0 * val);
Aug 22 '11 at 04:28 PM Bunny83

Thanks :)

Aug 23 '11 at 09:50 AM Dreeka
(comments are locked)
10|3000 characters needed characters left

If you want to display the float as string you should use a custom format string.

In your case

// C#
float val = 4.101814f;
Debuf.Log("The value is "+val.ToString("0.00"));
// prints: "The value is 4.10"

// UnityScript
var val = 4.101814f;
Debuf.Log("The value is "+val.ToString("0.00"));
// prints: "The value is 4.10"
more ▼

answered Aug 22 '11 at 04:39 PM

Bunny83 gravatar image

Bunny83
45.2k 11 49 207

Thanks :)

Aug 23 '11 at 09:50 AM Dreeka
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x342
x181
x23

asked: Aug 22 '11 at 03:33 PM

Seen: 451 times

Last Updated: Aug 23 '11 at 09:50 AM