분수를 유지하면서 문자열을 소수로 변환
나는 변환하려고 1200.00
에 decimal
만 Decimal.Parse()
제거합니다 .00
. 몇 가지 다른 방법을 시도했지만 .00
0이 아닌 분수를 제공하는 경우를 제외하고 는 항상 제거합니다 .
string value = "1200.00";
방법 1
var convertDecimal = Decimal.Parse(value , NumberStyles.AllowThousands
| NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol);
방법 2
var convertDecimal = Convert.ToDecimal(value);
방법 3
var convertDecimal = Decimal.Parse(value,
NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture);
어떻게 변환 할 수 있습니다 string
포함 1200.00
A를 decimal
포함 1200.00
?
흠 ... 재현 할 수 없습니다.
using System;
class Test
{
static void Main()
{
decimal d = decimal.Parse("1200.00");
Console.WriteLine(d); // Prints 1200.00
}
}
나중에 십진수 값을 정규화하는 코드의 다른 부분이 아니라고 확신합니까?
문화적 문제인 경우에 대비하여 로케일에 전혀 의존하지 않는이 버전을 사용해보십시오.
using System;
using System.Globalization;
class Test
{
static void Main()
{
decimal d = decimal.Parse("1200.00", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));
}
}
문제는 소수점을 표시 할 때가 아니라 내용이 아니라는 것입니다.
시도하면
string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString();
s
문자열이 포함됩니다 "1200"
.
그러나 코드를 이렇게 변경하면
string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString("0.00");
s
"1200.00"
원하는대로 문자열 을 포함합니다 .
편집하다
오늘 아침 일찍 뇌사 상태 인 것 같습니다. 나는 Parse
지금 진술을 추가했다 . 그러나 첫 번째 코드도 "1200"을 출력 할 것으로 예상 했더라도 "1200.00"을 출력합니다. 나는 매일 무언가를 배우는 것 같고,이 경우에는 분명히 아주 기본적인 것입니다.
따라서 이것은 적절한 대답을 무시하십시오. 이 경우 문제를 식별하려면 더 많은 코드가 필요할 것입니다.
안녕하세요 저는 같은 문제가 있었지만 간단합니다.
string cadena="96.23";
decimal NoDecimal=decimal.parse(cadena.replace(".",","))
나는 이것이 십진수에서 C #을 받아들이는 표기법이 ","와 함께 있기 때문이라고 생각한다.
아래 코드는 값을 1200.00으로 인쇄합니다.
var convertDecimal = Convert.ToDecimal("1200.00");
Console.WriteLine(convertDecimal);
무엇을 기대하는지 잘 모르시겠습니까?
CultureInfo 클래스 사용이 저에게 효과적이었습니다. 도움이 되었기를 바랍니다.
string value = "1200.00";
CultureInfo culture = new CultureInfo("en-US");
decimal result = Convert.ToDecimal(value, culture);
이 예 사용
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("en-GB",true);
decimal currency_usd = decimal.Parse(GetRateFromCbrf("usd"),culInfo);
decimal currency_eur = decimal.Parse(GetRateFromCbrf("eur"), culInfo);
여기에 내가 생각해 낸 해결책이 있습니다. 이것은 명령 프롬프트 프로젝트로 실행할 준비가되었습니다. 그렇지 않은 경우 몇 가지 물건을 청소해야합니다. 도움이 되었기를 바랍니다. 1.234.567,89 1,234,567.89 등과 같은 여러 입력 형식을 허용합니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Linq;
namespace ConvertStringDecimal
{
class Program
{
static void Main(string[] args)
{
while(true)
{
// reads input number from keyboard
string input = Console.ReadLine();
double result = 0;
// remove empty spaces
input = input.Replace(" ", "");
// checks if the string is empty
if (string.IsNullOrEmpty(input) == false)
{
// check if input has , and . for thousands separator and decimal place
if (input.Contains(",") && input.Contains("."))
{
// find the decimal separator, might be , or .
int decimalpos = input.LastIndexOf(',') > input.LastIndexOf('.') ? input.LastIndexOf(',') : input.LastIndexOf('.');
// uses | as a temporary decimal separator
input = input.Substring(0, decimalpos) + "|" + input.Substring(decimalpos + 1);
// formats the output removing the , and . and replacing the temporary | with .
input = input.Replace(".", "").Replace(",", "").Replace("|", ".");
}
// replaces , with .
if (input.Contains(","))
{
input = input.Replace(',', '.');
}
// checks if the input number has thousands separator and no decimal places
if(input.Count(item => item == '.') > 1)
{
input = input.Replace(".", "");
}
// tries to convert input to double
if (double.TryParse(input, out result) == true)
{
result = Double.Parse(input, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.InvariantCulture);
}
}
// outputs the result
Console.WriteLine(result.ToString());
Console.WriteLine("----------------");
}
}
}
}
인쇄 된 표현이 예상과 다른 경우에도 값은 동일합니다.
decimal d = (decimal )1200.00;
Console.WriteLine(Decimal.Parse("1200") == d); //True
프로그램에서이 메서드를 호출 할 수 있습니다.
static double string_double(string s)
{
double temp = 0;
double dtemp = 0;
int b = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '.')
{
i++;
while (i < s.Length)
{
dtemp = (dtemp * 10) + (int)char.GetNumericValue(s[i]);
i++;
b++;
}
temp = temp + (dtemp * Math.Pow(10, -b));
return temp;
}
else
{
temp = (temp * 10) + (int)char.GetNumericValue(s[i]);
}
}
return -1; //if somehow failed
}
예:
string s = "12.3";
double d = string_double (s); //d = 12.3
십진수 d = 3.00은 여전히 3입니다. 화면에 표시하거나 로그 파일에 3.00으로 인쇄하고 싶을 것 같습니다. 다음을 수행 할 수 있습니다.
string str = d.ToString("F2");
또는 데이터베이스를 사용하여 십진수를 저장하는 경우 데이터베이스에서 pricision 값을 설정할 수 있습니다.
이것이 당신이해야 할 일입니다.
decimal d = 1200.00;
string value = d.ToString(CultureInfo.InvariantCulture);
// value = "1200.00"
이것은 나를 위해 일했습니다. 감사.
참고 URL : https://stackoverflow.com/questions/4264736/convert-string-to-decimal-keeping-fractions
'Nice programing' 카테고리의 다른 글
git add -A는 디렉토리의 모든 수정 된 파일을 추가하지 않습니다. (0) | 2020.12.12 |
---|---|
NumPy가 뷰 또는 복사본을 생성하는지 어떻게 알 수 있습니까? (0) | 2020.12.12 |
Jenkins에서 "gradle"프로그램을 실행할 수 없습니다. (0) | 2020.12.11 |
matplotlib를 사용하여 모든 서브 플롯의 기본 색상주기를 설정하는 방법은 무엇입니까? (0) | 2020.12.11 |
설정이 다른 두 파일에 로깅 (0) | 2020.12.11 |