string 字符串 3 位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16465321/
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-09-09 01:55:08  来源:igfitidea点击:

String 3 decimal places

vb.netstringformat

提问by Alex

Example 1

示例 1

Dim myStr As String = "38"

I want my result to be 38.000...

我希望我的结果是38.000...



Example 2

示例 2

myStr = "6.4"

I want my result to be 6.400

我希望我的结果是 6.400



What is the best method to achieve this? I want to format a stringvariable with atleast three decimalplaces.

实现这一目标的最佳方法是什么?我想用至少三位小数来格式化字符串变量。

回答by GJKH

Use FormatNumber:

使用FormatNumber

Dim myStr As String = "38"
MsgBox(FormatNumber(CDbl(myStr), 3))

Dim myStr2 As String = "6.4"
MsgBox(FormatNumber(CDbl(myStr2), 3))

回答by Jodrell

So if you have

所以如果你有

Dim thirtyEight = "38"
Dim sixPointFour = "6.4"

Then, the best way to parse those to a numeric type is, Double.Parseor Int32.Parse, you should keep your data typed until you want to display it to the user.

然后,将它们解析为数字类型的最佳方法是,Double.Parse或者Int32.Parse,您应该保持数据的类型,直到您想将其显示给用户。

Then, if you want to format a string with 3 decimal places, do somthing like String.Format("{0:N3}", value).

然后,如果您想用 3 个小数位格式化字符串,请执行类似String.Format("{0:N3}", value).

So, if you want a quick hack for the problem,

所以,如果你想快速解决这个问题,

Dim yourString = String.Format("{0:N3}", Double.Parse("38"))

would do.

会做。

回答by giacomelli

Take a look on "Standard Numeric Format Strings"

看看“标准数字格式字符串”

float value = 6.4f;
Console.WriteLine(value.ToString("N3", CultureInfo.InvariantCulture));
// Displays 6.400

回答by Tony Hopkinson

In pseudo code

在伪代码中

decpoint = Value.IndexOf(".");
If decpoint < 0 
  return String.Concat(value,".000")
else
  return value.PadRight(3 - (value.length - decpoint),"0")

If it's string keep it as a string. If it's a number pass it as one.

如果它是字符串,请将其保留为字符串。如果是数字,则将其作为一传递。