String 3 decimal places

落花浮王杯 提交于 2019-12-19 05:24:06

问题


Example 1

Dim myStr As String = "38"

I want my result to be 38.000 ...


Example 2

myStr = "6.4"

I want my result to be 6.400


What is the best method to achieve this? I want to format a string variable with atleast three decimal places.


回答1:


Use FormatNumber:

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

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



回答2:


So if you have

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

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

Then, if you want to format a string with 3 decimal places, do somthing like 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.




回答3:


Take a look on "Standard Numeric Format Strings"

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



回答4:


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.



来源:https://stackoverflow.com/questions/16465321/string-3-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!