使用货币字符串格式时防止小数舍入 [英] prevent rounding of decimals when using currency string format

查看:42
本文介绍了使用货币字符串格式时防止小数舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些来自外部服务的十进制数据.我需要将数据格式化为2位小数,因为它代表金钱,但是如果我使用标准C格式,我会舍入数字:

I have some decimal data coming from an external service. I need to format the data to 2 decimal places as it is represents money, but if I use the standard C format, I rounds the number:

var x = 42.999m;

var y = string.Format("{0:C}", x);

这将导致y包含£43.00.我如何将其四舍五入到42.99英镑?

This results in y containing £43.00. How can I have it round down to £42.99?

(请注意,这个问题不一样)

推荐答案

如果要使用非默认的舍入策略,则需要执行以下操作:

If you want to use a non-default rounding strategy, you'd need to do something like:

var x = 42.999m;

var y = string.Format("{0:C}", Math.Floor(x * 100) / 100);

Math.Floor 向下舍入;但是,它不占用小数位数,因此您必须强制使用小数点后两位的行为.

Math.Floor rounds down; however it doesn't take a number of decimal places, so you have to force the 2 decimal place behaviour.

这篇关于使用货币字符串格式时防止小数舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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