我无法删除小数 C# Unity

me *_* me 0 c# decimal unity-game-engine

我正在使用 Unity3D 和 C# 制作汽车游戏,我想显示速度,但我无法删除小数。请帮忙。

我已经搜索了一个多小时,但没有解决我的问题。

var speed = Convert.ToString(GetComponent<Rigidbody>().velocity.magnitude * 3.6); 
speed = String.Format("{0:C0}", speed);
Camera.FindObjectOfType<TextMesh>().text = speed;
Run Code Online (Sandbox Code Playgroud)

截屏

der*_*ugo 5

您传递string

String.Format("{0:C0}", speed);
Run Code Online (Sandbox Code Playgroud)

格式化程序仅适用于数值(int, float, double, ...),不适用于 a string

另请参阅有关自定义数字格式字符串标准数字格式字符串的更多信息,因为"C0"它适用于Currency您要查找的内容,但可能不是您要查找的内容。您可能想要使用"N0"forNumeric或简单地使用自定义字符串,如下所示。

您并没有真正指定您的输出究竟应该是什么样子,以及您是否想要截断所有小数或仅达到特定精度。


而是直接传递它就像

                                      // Also note the f here for a float multiplication!
                                      //                       |
                                      //                       v
var speed = (GetComponent<Rigidbody>().velocity.magnitude * 3.6f).ToString("0.00"); 
Run Code Online (Sandbox Code Playgroud)

或者

var speed = (GetComponent<Rigidbody>().velocity.magnitude * 3.6f).ToString("0"); 
Run Code Online (Sandbox Code Playgroud)

或者,您也可以按照评论中提到的方式使用Mathf.RoundToInt,以便首先舍入为 int 值

var speed = Mathf.RoundToInt(GetComponent<Rigidbody>().velocity.magnitude * 3.6f).ToString(); 
Run Code Online (Sandbox Code Playgroud)

边注:

关于效率的最后一个旁注:

似乎您想在例如Update反复使用它......不要!

而是只在游戏开始时使用FindandGetCompnent一次,稍后再使用引用:

// if possible even reference this in the Inspector right 
// away than you don't need the Awake method at all
[SerializeField] private RigidBody rigidBody;
[SerializeField] private TextMesh textMesh;

privtae void Awake()
{
    if(!rigidBody) rigidBody = GetComponent<Rigidbody>();
    if(!textMesh) textMesh = Camera.FindObjectOfType<TextMesh>();
}

privtae void Update()
{
    var speed = Convert.ToString(rigidBody.velocity.magnitude * 3.6); 
    speed = String.Format("{0:C0}", speed);
    textMesh.text = speed;
}
Run Code Online (Sandbox Code Playgroud)