将字符串转换为十进制以始终具有2个小数位 [英] Convert string to decimal to always have 2 decimal places

查看:114
本文介绍了将字符串转换为十进制以始终具有2个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串转换为十进制,以便始终将其保留两位小数。例如:

I'm trying to convert a string to a decimal to always have 2 decimal places. For example:


  • 25.88-> 25.88

  • 25.50-> 25.50

  • 25.00-> 25.00

但是在下面的代码中,我看到了以下内容:

But with my code below i'm seeing the following:


  • 25.88-> 25.88

  • 25.50-> 25.5

  • 25.00-> 25

我的代码:

Decimal.Parse("25.50", CultureInfo.InvariantCulture);

OR

Decimal.Parse("25.00");

OR

Convert.ToDecimal("25.50");

我得到的全部 25.5 。是否可以不切断多余的

For all I get 25.5. Is it possible to not cut off the excess zeros?

推荐答案

十进制是一种有点奇怪的类型,因此,从技术上讲,您可以做一点(可能是)技巧:

Decimal is a bit strange type, so, technically, you can do a little (and may be a dirty) trick:

  // This trick will do for Decimal (but not, say, Double) 
  // notice "+ 0.00M"
  Decimal result = Convert.ToDecimal("25.5", CultureInfo.InvariantCulture) + 0.00M; 

  // 25.50 
  Console.Write(result);

但是更好的方法是格式化(代表十进制到小数点后两位,只要要输出即可:

But much better approach is formatting (representing) the Decimal to 2 digits after the decimal point whenever you want to output it:

  Decimal d = Convert.ToDecimal("25.50", CultureInfo.InvariantCulture);

  // represent Decimal with 2 digits after decimal point
  Console.Write(d.ToString("F2"));

这篇关于将字符串转换为十进制以始终具有2个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆