C# – 限制双精度变量保留两位小数

huangapple go评论61阅读模式
英文:

C# - Restrict double variable to two decimal places

问题

我正在使用Unity引擎制作游戏。
我正在使用一个双精度变量,希望它只显示到小数点后两位。

public double nos = 0;

例如:如果nos等于17.2369...;
我希望它显示nos为17.23;

附注:我不想四舍五入或其他处理方式。
如何实现这一点?

英文:

I am using Unity Engine to make a game.
I am using a double variable and want it to only display the number till two decimal places.

public double nos = 0;

For eg: if nos = 17.2369...;
I want it to display nos = 17.23;

P.S.: I don't want to round it off or smt.

How to make that happen?

答案1

得分: 0

你说得对,字符串格式化也进行了一些四舍五入。那么应该这样做:

double num = 15.345324;
num = Math.Truncate(100 * num) / 100;
// num = 15.34

使用10的幂次方作为小数位数的因子(这里是100)。

100 -> 2位小数

1000 -> 3位小数

等等。

编辑:更一般的方式可以这样做

double num = 12.3456789;
double numOfDecimals = 2;
num = Math.Truncate(Math.Pow(10, numOfDecimals) * num) / Math.Pow(10, numOfDecimals);
英文:

You are right, string formatting also does some rounding.
This should work then:

double num = 15.345324;
num = Math.Truncate(100 * num) / 100;
// num = 15.34

Use 10 to the power of decimal places (here: 100) you want to have as factor.

100 -> 2dps

1000 -> 3dps

etc.

Edit: In a more general way one could do sth like this

double num = 12.3456789;
double numOfDecimals = 2;
num = Math.Truncate(Math.Pow(10, numOfDecimals) * num) / Math.Pow(10, numOfDecimals);

huangapple
  • 本文由 发表于 2023年3月12日 18:21:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712466.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定