Convert string to currency format without casting to numerical value first

This code is

Convert.ToDecimal("28.9100000000000000").ToString("c") 

converts a string containing a decimal value into a nicely formatted currency value. Is there a way to do this without first converting the string value to a decimal number?

+4
source share
3 answers

To preserve currency-specific currency attributes (currency symbol, delimiters, and precision), your current approach looks like the best.

If you know the accuracy and don’t care about cultures, you can do a few simple string manipulations:

  "$" & myString.Substring(0, myString.IndexOf(".") + 3) 
+3
source

A simple method that I use:

 MoneyString = string.format("{0:C}",DecimalValue) 
+4
source

How about this?

 decimalString = "28.910000000000000000" currencyString = "$" + decimalString.SubString(0, decimalString.IndexOf('.') + 3) 

Of course, if you are going to do this, you also need to worry about locale settings. It's probably just as easy to do a numerical conversion and let the framework do the formatting for you.

+1
source

Source: https://habr.com/ru/post/1403873/


All Articles