C# 带有 3 个尾随小数位、一个十进制千位分隔符和后面的逗号的格式数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16466645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:04:24  来源:igfitidea点击:

format number with 3 trailing decimal places, a decimal thousands separator, and commas after that

c#string-formattingcultureinfonumber-formatting

提问by Brett

This is probably a simple question, and I'm sure there's a way to do it with string.format(), NumberFormatInfo, CultureInfoor some combination of them, but I need to display large numeric values with 3 trailing decimal places, a decimal instead of a comma for the thousands separator, and then a comma for the millions separator and up.

这可能是一个简单的问题,我敢肯定有办法做到这一点的string.format()NumberFormatInfoCultureInfo或其中的一些组合,但我需要3尾随小数显示大数值,小数,而不是为成千上万的一个逗号分隔符,然后是数百万分隔符及以上的逗号。

The input is either a whole number or a number followed by up to three decimal places (20000, 123.456, 12.2)

输入是整数或后跟最多三位小数的数字(20000、123.456、12.2)

For example:

例如:

142650 should display as 142,650.000

142650 应显示为 142,650.000

11200.50 should display as 11,200.500

11200.50 应显示为 11,200.500

123.456 should remain 123.456

123.456 应该保持在 123.456

I suppose it's the same as dividing the value by 1000 and then using string.format("{0:f3}", value), but I was hoping to find something that didn't take arithmetic.

我想这与将值除以 1000 然后使用 相同string.format("{0:f3}", value),但我希望找到不需要算术的东西。

String.Format("{0:#,#.000}", value)gets me close, but it puts a leading 0 on small numbers, so 1.256 is displaying as 01.256, when I need it to remain just 1.256

String.Format("{0:#,#.000}", value)让我接近,但它在小数字上放置了一个前导 0,所以 1.256 显示为 01.256,当我需要它保持为 1.256 时

采纳答案by Brett

The format String.Format("{0:#,0.000}", value)ended up doing it for me. It works for whole numbers and numbers with anywhere from 1 to 3 trailing decimal places.

格式String.Format("{0:#,0.000}", value)最终为我做了。它适用于整数和带有 1 到 3 个尾随小数位的数字。