Convert decimal to string without commas or dots

后端 未结 8 1099
盖世英雄少女心
盖世英雄少女心 2021-01-12 07:15

In .NET, I need to convert a decimal amount (money) to a numbers-only string, i.e: 123,456.78 -> 12345678

I thought

var dotPos = amount.ToString().L         


        
相关标签:
8条回答
  • 2021-01-12 07:33

    I think this is what you're looking for:

    value.ToString("D")
    

    http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

    0 讨论(0)
  • 2021-01-12 07:34

    You say it's an amount, so I expect 2 digits after the decimal. What about:

     var amountstring = (amount * 100).ToString();
    

    to get the cents-value without delimiters?

    Or maybe even

    var amountString = ((int)(amount * 100)).ToString();
    

    to make sure no decimals remain.

    0 讨论(0)
  • 2021-01-12 07:37
    var amountString = amount.ToString().Replace(",",string.Empty).Replace(".",string.Empty);
    

    This will replace all the "," commas and "." decimal from the amount.

    0 讨论(0)
  • 2021-01-12 07:38

    You don't need casts, you don't need to know where the decimal is, and you certainly don't need Linq. This is literally a textbook-case of Regular Expressions:

    Regex regx = new Regex("[^0-9]");
    var amountString = regx.Replace(amount, "");
    

    Couldn't be simpler. And you can pass it strings with other odd monetary characters, or any character at all, and all you will get out is the decimal string.

    0 讨论(0)
  • 2021-01-12 07:39
    var amountString = amount.ToString().Replace(".","").Replace(",","");
    
    0 讨论(0)
  • 2021-01-12 07:47
    var amount = 123456.78;
    var amountString = amount.ToString().Replace(",", "").Replace(".","");
    
    0 讨论(0)
提交回复
热议问题