如何用上标的力量用科学计数法格式化数字 [英] How to format numbers in scientific notation with powers in superscript
问题描述
我需要写如下值:
9.6 x 10²
9.6 x 10¹²
我需要知道是否可以在字符串中设置如上所述的数字格式.
I need to know if there is a way to format numbers as above in a string.
推荐答案
作为我上面的评论的后续内容-做这样的事情符合您的要求:
As a follow up to my comment above - does something like this do what you require :
public String FormatAs10Power(decimal val)
{
string SuperscriptDigits = "\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079";
string expstr = String.Format("{0:0.#E0}", val);
var numparts = expstr.Split('E');
char[] powerchars = numparts[1].ToArray();
for (int i = 0; i < powerchars.Length; i++)
{
powerchars[i] = (powerchars[i] == '-') ? '\u207b' : SuperscriptDigits[powerchars[i] - '0'];
}
numparts[1] = new String(powerchars);
return String.Join(" x 10",numparts);
}
请参阅: https://dotnetfiddle.net/dX7LAF
根据我上面的评论-数字首先转换为指数格式字符串(在C#中将字符串/整数转换为上标),再转换回字符串&这两个部分使用"x 10"作为新的分隔符组合.
As per my comment above - the number is first converted to an exponential format string (https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#EFormatString), that string is then split on the exponential separator 'E'. The first array is the numeric part, the second the power of 10 to which it is raised - this is converted to superscript characters using one of the techniques of the link I gave (Convert a string/integer to superscript in C#), converted back to a string & the two parts combined using "x 10" as the new separator.
根据您的示例,我假设您希望该值具有一位数的精度,并且不带+号.如果您还有其他需要,可以将格式作为参数传递.上标+的代码是'\ u207A'.这里有一个链接(在撰写本文时)提供上标代码列表: http://unicode.org/charts/PDF/U2070.pdf
I have assumed you want the value to single digit precision as per your example with no preceding + sign. If you need anything else you could pass the format as a parameter. The code for superscript + is '\u207A'. There is a link here (at the time of writing) giving the list of superscript codes : http://unicode.org/charts/PDF/U2070.pdf
这篇关于如何用上标的力量用科学计数法格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!