使用 ToString 方法可以将 float 类型的小数保留两位。

例如:

float f = 3.1415926f;
string s = f.ToString('f2'); // 将f保留两位小数,s的值为'3.14'

另外,也可以使用 Math.Round 方法将 float 类型的小数保留两位:

float f = 3.1415926f;
float result = (float)Math.Round(f, 2); // 将f保留两位小数,result的值为3.14
C# 浮点数保留两位小数的两种方法

原文地址: https://www.cveoy.top/t/topic/nVyg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录