简体   繁体   English

如何在C#中固定十进制值的点

[英]How do i fix point in decimal value in C#

I have code in VB.net in below: 我在下面的VB.net中有代码:

me.Index = Format(Convert.ToDouble(g.Trim()), "##.##")

result : 120.00 结果:120.00

how do i same thing in C#. 我如何在C#中做同样的事情。 I don't use format function in C#. 我不在C#中使用格式功能。 I just want result will not place more then two value after point. 我只希望结果不会在点之后放置两个以上的值。 i mean if i send value 120.120000 then result will be 12.12 我的意思是如果我发送值120.120000,那么结果将是12.12

It's not clear what you mean by "I don't use format function in C#" but of course you could use string.Format . 您不清楚“我不在C#中使用格式函数”的意思是什么,但是您当然可以使用string.Format However, using double.ToString would probably be simpler: 但是,使用double.ToString可能会更简单:

Index = Convert.ToDouble(g.Trim()).ToString("0.##");

(I've changed the leading ## to 0 to ensure that there's always a leading digit, so you don't get ".5" for example. Obviously if you really want the leading digits to be optional, change it to "#.##" . I don't see a benefit in using ## as a prefix though.) (我将前导##更改为0以确保始终有一个前导数字,因此您不会得到“ .5”。显然,如果您确实希望前导数字是可选的,请将其更改为"#.##" 。不过,使用##作为前缀并没有好处。)

However: 然而:

  • This will use the current culture's decimal separator; 这将使用当前区域性的小数点分隔符; is that what you want, or do you always want to use . 是您想要的,还是您始终想使用的. ?
  • If the decimal representation of the number is important, you may well not want to use double at all. 如果数字的小数表示很重要,则您可能根本不想使用double Are you sure you shouldn't be using decimal ? 您确定不应该使用decimal吗?

你可以这样

decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);

Either you use this 你要么用这个

var value = 2.346;
var str = value.ToString("0.00");

or 要么

decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero); //as in msdn site which rounds a decimal value to a specified precision. //如msdn网站中所述,它将十进制值舍入为指定的精度。

or use Round function like this 或像这样使用Round函数

decimal a = 1.994444M;

Math.Round(a, 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM