【问题标题】:Long integer to readable string [duplicate]长整数到可读字符串[重复]
【发布时间】:2015-02-14 10:27:40
【问题描述】:

我希望能够将很长的整数转换为可读的字符串

这从 1500 (1.50k) 到 12.500.000.000 是 12.50b 等等,然后是不可读的数字,这些数字将被标记为 A,然后是 B 等等。

现在我很确定有一个漂亮的逻辑表明如果整数的字符串长度为 9,那么点应该在位置 3 和 6 或其他位置。

我的数学(及其可编程逻辑)对我来说是不存在的,所以任何人都可以帮助我吗?

这是我现在混乱且不可重复使用的尝试:

int val = 150050004;
string theValue = val.ToString();
int valLength = theValue.Length;

string newVal = theValue;
if (valLength == 7) {
    newVal = theValue.Substring(0, 1) +"."+ theValue.Substring(1, 2);
}

if (valLength == 8) {
    newVal = theValue.Substring(0, 2) +"."+ theValue.Substring(2, 2);
}

if (valLength == 9) {
    newVal = theValue.Substring(0, 3) +"."+ theValue.Substring(3, 2);
}

if (valLength > 6 && valLength < 10) {
    newVal = newVal + "m";
}

newVal 输出150.05m

【问题讨论】:

  • 我认为使用 m 表示百万会令人困惑,因为它是 1/1000 的 SI 前缀。
  • 举个例子,真的。它应该适用于所有字母,无论是 K、T、B、M 等。

标签: c# math decimal-point


【解决方案1】:

试试这个用“。”打断。 :

NumberFormatInfo numFormat = new NumberFormatInfo();
numFormat.NumberDecimalSeparator = ",";
numFormat.NumberGroupSeparator = ".";

long val = 12345678912345;
String result = val.ToString("#,##0",numFormat);

要添加后缀信息,请执行以下操作:

String result = null;
if (val / 1000000000 > 1)
    result = val.ToString("#,##0,#,,B",numFormat);
else if (val / 1000000 > 1)
    result = val.ToString("#,##0,#,M", numFormat);
else if (val / 1000 > 1)
    result = val.ToString("#,##0,#K", numFormat);
else
    result = val.ToString("#,##0", numFormat);

【讨论】:

  • 这似乎是小数。我认为:"#,##0"
  • 我收到error CS0103: The name String' does not exist in the current context 错误?
  • 你是对的,它是一个“,”
  • 啊,和using System; 一起工作(现在我的Random 坏了?)。尽管如此;这样的字符串非常易读。我现在可以轻松地将其子串化为较小的值吗?像 150.05M 而不是 150,050,004?
  • 可以,我更新了答案
猜你喜欢
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 2013-02-26
  • 2018-12-30
  • 2018-11-09
相关资源
最近更新 更多