Substring Error : ArgumentOutOfRangeException: Cannot be negative. Parameter name: length

public string LapTimeStr=“00.00000”;

update()
{
LapTime=Time.time;
LapTimeStr=LapTime.ToString();
LapTimeStr=LapTimeStr.Substring(0,LapTimeStr.Length-3);
}
this is giving me an error.

ArgumentOutOfRangeException: Cannot be negative.
Parameter name: length.

can any1 help me??

Of course it gives this error. If the string length is lesser than 3, then Length-3 is lesser than zero.

If your purpose is to retrieve the integer part of the time, then do something like that instead:

// convert time (float) into integer
int nLapTime = (int) Time.time; // or round the value using Mathf.RoundToInt(Time.time);
LapTimeStr = nLapTime.ToString();

But if you want to keep two digits, then format the string:

LapTimeStr = LapTime.ToString("F2");  // F means float, and 2 is the number of digits

Your code doesn’t make much sense :wink:

Why do you want to remove the last 3 characters of the string? I guess you want to shorten the float numbers fractional part, but it doesn’t work that way since is the float is for example exactly 3.0, ToString() will return “3”. Now you call your Substring function with (0,-2) and this doesn’t make sense.

If you want a specific string format, use the format-string version of ToString(fmtStr)

LapTime = Time.time;
LapTimeStr = LapTime.ToString("0.00");

this will always return a string with at least one digit before and always 2 after the decimal point. If you use “00.00” it will return at least 2 digits before the DP.

Examples with (LapTimeStr = LapTime.ToString(“00.00”)):

LapTime    LapTimeStr
  0         00.00
  0.123     00.12
  1.888     01.88
 76.789     76.78
245.045    245.04