2011-02-09 2 views
4

У меня есть сумма в долларах, 23,15. Я хочу отформатировать его так, чтобы я мог вернуться только 0,15 или 15, так как хочу разместить только центы в теге html <sup>.Формат строки для центов только в C#

Чтобы вернуть доллары только я использовал {0:C0} или без знака $ {0:N0}

Edit: Видимо {0:C0} и {0:N0} не будет работать для меня, как округлить до целого числа :(

+0

Хоув вы пробовали формат строки как {} .00? У меня нет VS open, поэтому я не могу проверить, но может работать – Andrey

+0

@ Andrey, просто попробовал это, возвращает целое число. –

ответ

5

Если вам нужна строка с HTML-тегов, которые вы можете использовать что-то вроде этого:

var decimalValue = 23.15m; 
string value2 = decimalValue.ToString("$ #.<sup>##</sup>"); //$ 23.<sup>15</sup> 

Кроме того, если вы хотите составить с центов вместо

var value = String.Format("{0:C0}", decimalValue); // $23 

Используйте

var value = String.Format("{0:C2}", decimalValue); // $23.15 

Нулевая после 'C' в формате '{0: C0}' означает количество знаков после точки.

+0

Спецификатор '{0: C}' возвращает '$ 123.46' для меня для ввода из '123.4567M' - это не похоже на то, что он хочет – BrokenGlass

+0

Это ответ на другой вопрос:« Редактировать: По-видимому {0: C0} и {0: N0} не будут работать для меня, поскольку они округляются до целого числа: (' –

+0

Я использовал ваш первый пример: C0 не показывает центов, но он также округляет сумму в долларах. Кроме того, в моем случае мне никогда не понадобится количество, которое находится в тысячах, но если бы я сделал как я могу сделать первый пример сделать это автоматически? –

0

Не основной путь, но будет работать :)

dollarAmount - Math.Floor(dollarAmount) 

будет получать центов (в вашем образце получите 0,15).

+0

это один из способов сделать это, я бы предпочел использовать оператор формата, если он есть, так как он чище. –

+0

Yup, для этого должна быть какая-то форматная строка, я просто не слишком хорошо помню их, поэтому иногда я просто использую алгебру вместо этого :) – Andrey

0

Программа класса { статической силы основных (String [] арг)

{ 

     double Num; 
     // declaring "Num" as a double 

     Console.WriteLine("Please enter dollar and cents amount\nExample: 4.52"); 
     //This bit of code informs the user what type of information you want from them 

     Num = double.Parse(Console.ReadLine()); 
     //assigns "Num" to the users input and sets the user input as numerical value and stores it in the temporary memory 

     Console.WriteLine("You have {1} dollars and {2} cents from {0:c}.", Num, WhyAreWeDoingThis(ref Num), Num); 
     //returns the values requested and sends "Num" through the program to separate dollars from cents. 
     //first: off in{0:c} it takes the original user input and gives it the dollar sign$ due to the additional code to the left of the zero as shown {0:c} 
     //second: "Num" is sent to the WhyAreWeDoingThis Method through the reference method "ref" where the dollar amount is separated from the cent amount 
     //*Note* this will only return the dollar amount not the cents* 
     //Third: the second "Num" referred to at this point is only the remaining cents from the total money amount. 
     //*Note* this is because the program is moving "Num" around as a stored value from function to function not grabbing the users original input every time. 

     Console.ReadLine(); 
     //this keeps the program open 

    } 
    static int WhyAreWeDoingThis(ref double A) 
     // reference method 
     //*Note* it is set as a "static int" and (ref double) 

    { 
     int dd = (int)A; 
     //this turn the double into a temporary integer by type casting for this one operation only. 
     A = A % dd; 
     //Separates the dollars from the cents leaving only the cents in the "Num" value through the Modulus Operand. 
     return dd; 
     //returns the dollar amount. 
    } 
} 
+0

, пожалуйста, напишите подробный ex с его кодом, его непонятным сейчас. – Pawan

Смежные вопросы