使用字符串格式显示最多 2 位小数或简单整数

编程入门 行业动态 更新时间:2024-10-24 07:29:01
本文介绍了使用字符串格式显示最多 2 位小数或简单整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个要显示的价格字段,有时可以是 100 或 100.99 或 100.9,我想要的是仅在为该价格输入小数位时以 2 位小数显示价格,例如,如果它是 100它应该只显示 100 而不是 100.00,如果价格是 100.2,它应该同样显示 100.20,因为 100.22 应该是一样的.我用谷歌搜索并发现了一些示例,但它们与我想要的不完全匹配:

I have got a price field to display which sometimes can be either 100 or 100.99 or 100.9, What I want is to display the price in 2 decimal places only if the decimals are entered for that price , for instance if its 100 so it should only show 100 not 100.00 and if the price is 100.2 it should display 100.20 similarly for 100.22 should be same . I googled and came across some examples but they didn't match exactly what i wanted :

// just two decimal places String.Format("{0:0.00}", 123.4567); // "123.46" String.Format("{0:0.00}", 123.4); // "123.40" String.Format("{0:0.00}", 123.0); // "123.00"

推荐答案

不雅的方式是:

var my = DoFormat(123.0);

DoFormat 类似于:

public static string DoFormat( double myNumber ) { var s = string.Format("{0:0.00}", myNumber); if ( s.EndsWith("00") ) { return ((int)myNumber).ToString(); } else { return s; } }

不优雅,但在某些项目的类似情况下对我有用.

Not elegant but working for me in similar situations in some projects.

更多推荐

使用字符串格式显示最多 2 位小数或简单整数

本文发布于:2023-11-10 06:16:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574581.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最多   小数   整数   字符串   简单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!