Что такое double parse

Double.parse(): независимость от региональных настроек

Что такое double parse. Смотреть фото Что такое double parse. Смотреть картинку Что такое double parse. Картинка про Что такое double parse. Фото Что такое double parseМожно ли заставить double.Parse обрабатывать числа с разными разделителями?
Привет! Есть фреймворк, который подключен к проекту в виде библиотеки. В одном из сценариев.

Что такое double parse. Смотреть фото Что такое double parse. Смотреть картинку Что такое double parse. Картинка про Что такое double parse. Фото Что такое double parseПроблемы с кодировкой при отправке запроса в IE и IIS 7 после смены региональных настроек
Здравствуйте! Имеется таблица с редактируемыми строками. После нажатия на сохранить, формирую.

Как отучить C# от региональных настроек?
в моей программе я хочу чтобы работало 0.000067 (разделитель точка) в независимости от того что.

Mikant, Вы могли быть привести пример вашей реализации, того что вы имеете ввиду? пожалуйста.

Такого мои пользователи обычно не вводят. Им не извращаться надо, а параметр задать. Не думая при этом о точках и запятых.

В случае исключения я дисаблю кнопку ОК и крашу едит контрол красным цветом.
Так что программа защищёна от попыток свалить её посредством ввода ерунды в качестве коэффициента.

Инвариантную культуру я применяю для того, чтобы парсер правильно обработал точку, а не для того, чтобы задействовать весь функционал инвариантной культуры.

Определенный формат ввода сделан по запросу пользователей?

Дисклаймер: в моем сообщении нет наездов или попыток поучать (почему-то некоторые это в моих сообщениях видят). Всего лишь пытаюсь вести продуктивную дискуссию с коллегами о юзабилити пользовательских интерфейсов.

Ваши, пользователи, похоже, привыкли работать с большими числами и им удобнее делать так. Вам пришлось учесть эту особенность. Никто и не сомневался в том, что это вам успешно удалось.

Это вовсе не значит, что теперь из-за этого другие подходы неправомерны. Просто они для разных групп пользователей.

То есть получается, что юзабилити вне контекста применения не существует. Нужно учитывать специфику работы целевого пользователя.

Источник

Double. Try Parse Метод

Определение

Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Преобразует строковое представление числа в эквивалентное ему число двойной точности с плавающей запятой. Возвращает значение, указывающее, успешно ли выполнено преобразование.

Перегрузки

Преобразует диапазон символов, содержащий строковое представление числа в указанном стиле и с использованием формата, соответствующего данному языку и региональным параметрам, в эквивалентное ему число с плавающей запятой двойной точности. Возвращает значение, указывающее, успешно ли выполнено преобразование.

Преобразует строковое представление числа в эквивалентное ему число двойной точности с плавающей запятой. Возвращает значение, указывающее, успешно ли выполнено преобразование.

Преобразует представление диапазона числа указанного стиля, выраженное в формате, соответствующем определенному языку и региональным параметрам, в эквивалентное ему число двойной точности с плавающей запятой. Возвращает значение, указывающее, успешно ли выполнено преобразование.

Преобразует строковое представление числа указанного стиля, выраженное в формате, соответствующем определенному языку и региональным параметрам, в эквивалентное ему число двойной точности с плавающей запятой. Возвращает значение, указывающее, успешно ли выполнено преобразование.

Комментарии

Преобразует диапазон символов, содержащий строковое представление числа в указанном стиле и с использованием формата, соответствующего данному языку и региональным параметрам, в эквивалентное ему число с плавающей запятой двойной точности. Возвращает значение, указывающее, успешно ли выполнено преобразование.

Параметры

Диапазон символов только для чтения, содержащий преобразуемое число.

Объект, который предоставляет сведения о форматировании параметра s в зависимости от языка и региональных параметров.

Возвращаемое значение

Комментарии

Применяется к

TryParse(String, Double)

Преобразует строковое представление числа в эквивалентное ему число двойной точности с плавающей запятой. Возвращает значение, указывающее, успешно ли выполнено преобразование.

Параметры

Строка, содержащая преобразуемое число.

Возвращаемое значение

Примеры

В следующем примере метод используется TryParse(String, Double) для преобразования строковых представлений числовых значений в Double значения. Предполагается, что en-US является текущим языком и региональными параметрами.

Комментарии

Эта перегрузка отличается от Double.Parse(String) метода путем возвращения логического значения, которое указывает, завершилась ли операция синтаксического анализа, а не возвращать проанализированное числовое значение. Это исключает необходимость использования обработки исключений для проверки FormatException в случае, если событие s является недопустимым и его невозможно успешно проанализировать.

Протокол писать [целые числа,] целые цифры [. [ дробные цифры]] [e [знак] экспоненциальные цифры] [ws]

Элементы в квадратных скобках являются необязательными. Каждый из элементов описан в таблице ниже.

ЭлементОписание
wsПоследовательность пробельных символов.
signЗнак отрицательного или положительного знака.
целые числаПоследовательность числовых символов в диапазоне от 0 до 9, которые указывают целую часть числа. Целочисленные цифры могут отсутствовать, если есть дробные разряды.
,Символ разделителя группы, зависящий от языка и региональных параметров.
.Символ десятичной запятой, зависящий от языка и региональных параметров.
Дробные разрядыПоследовательность числовых символов в диапазоне от 0 до 9, которые указывают дробную часть числа.
EПрописная или строчная буква «e», которая указывает на экспоненциальную (экспоненциальную) нотацию.
экспоненциальные цифрыПоследовательность числовых символов в диапазоне от 0 до 9, задающих показатель степени.

Дополнительные сведения о числовых форматах см. в разделе Типы форматирования.

s Параметр анализируется с помощью сведений о форматировании в NumberFormatInfo объекте, инициализированном для текущего языка и региональных параметров системы. Для получения дополнительной информации см. NumberFormatInfo.CurrentInfo. Чтобы выполнить синтаксический анализ строки, используя сведения о форматировании некоторых других указанных региональных параметров, используйте Double.TryParse(String, NumberStyles, IFormatProvider, Double) перегрузку метода.

См. также раздел

Применяется к

Преобразует представление диапазона числа указанного стиля, выраженное в формате, соответствующем определенному языку и региональным параметрам, в эквивалентное ему число двойной точности с плавающей запятой. Возвращает значение, указывающее, успешно ли выполнено преобразование.

Параметры

Диапазон символов, содержащий строковое представление числа, которое нужно преобразовать.

Возвращаемое значение

Комментарии

Применяется к

TryParse(String, NumberStyles, IFormatProvider, Double)

Преобразует строковое представление числа указанного стиля, выраженное в формате, соответствующем определенному языку и региональным параметрам, в эквивалентное ему число двойной точности с плавающей запятой. Возвращает значение, указывающее, успешно ли выполнено преобразование.

Параметры

Строка, содержащая преобразуемое число.

Интерфейс IFormatProvider предоставляет сведения о форматировании параметра s для соответствующего языка и региональных параметров.

Возвращаемое значение

Исключения

style не является значением NumberStyles.

-или- style включает значение AllowHexSpecifier.

Примеры

В следующем примере демонстрируется использование Double.TryParse(String, NumberStyles, IFormatProvider, Double) метода для синтаксического анализа строкового представления чисел с определенным стилем и форматирования с использованием соглашений определенного языка и региональных параметров.

Комментарии

TryParseМетод похож на Parse(String, NumberStyles, IFormatProvider) метод, за исключением того, что этот метод не создает исключение в случае сбоя преобразования. Если преобразование выполнено, возвращается значение, true а result для параметра задается результат преобразования. Если преобразование завершается неудачно, возвращается значение, false а result параметр устанавливается в нуль. Это избавляет от необходимости использовать обработку исключений для проверки FormatException в случае, если событие s является недопустимым и не может быть успешно проанализировано.

style Параметр определяет допустимый формат s параметра для выполнения операции синтаксического анализа. Он должен представлять собой сочетание битовых флагов из NumberStyles перечисления. Следующие NumberStyles члены не поддерживаются:

Протокол [$] писать [целые числа,] целочисленные цифры [. дробные цифры] [e [знак] экспоненциальные цифры] [ws]

Элементы в квадратных скобках ([и]) являются необязательными. Каждый из элементов описан в таблице ниже.

Все завершающие символы NUL (U + 0000) в s игнорируются операцией синтаксического анализа, независимо от значения style аргумента.

provider Параметр является IFormatProvider реализацией, например NumberFormatInfo CultureInfo объектом или. provider Параметр предоставляет сведения, зависящие от языка и региональных параметров, используемые при анализе. Если provider параметр имеет значение null или NumberFormatInfo объект не может быть получен, используется информация о форматировании для текущего языка и региональных параметров.

Источник

Double. Try Parse Method

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Overloads

Converts a character span containing the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Converts the span representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Remarks

Converts a character span containing the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Parameters

A read-only character span that contains the number to convert.

Returns

Remarks

Applies to

TryParse(String, Double)

Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Parameters

A string containing a number to convert.

Returns

Examples

The following example uses the TryParse(String, Double) method to convert the string representations of numeric values to Double values. It assumes that en-US is the current culture.

Remarks

This overload differs from the Double.Parse(String) method by returning a Boolean value that indicates whether the parse operation succeeded instead of returning the parsed numeric value. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.

The s parameter can contain the current culture’s NumberFormatInfo.PositiveInfinitySymbol, NumberFormatInfo.NegativeInfinitySymbol, NumberFormatInfo.NaNSymbol (the string comparison is case-sensitive), or a string of the form:

Elements in square brackets are optional. The following table describes each element.

ElementDescription
wsA series of white-space characters.
signA negative sign or positive sign symbol.
integral-digitsA series of numeric characters ranging from 0 to 9 that specify the integral part of the number. Integral-digits can be absent if there are fractional-digits.
,A culture-specific group separator symbol.
.A culture-specific decimal point symbol.
fractional-digitsA series of numeric characters ranging from 0 to 9 that specify the fractional part of the number.
EAn uppercase or lowercase character ‘e’, that indicates exponential (scientific) notation.
exponential-digitsA series of numeric characters ranging from 0 to 9 that specify an exponent.

For more information about numeric formats, see Formatting Types.

The s parameter is parsed using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. For more information, see NumberFormatInfo.CurrentInfo. To parse a string using the formatting information of some other specified culture, use the Double.TryParse(String, NumberStyles, IFormatProvider, Double) method overload.

If a separator is encountered in the s parameter during a parse operation, and the decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

See also

Applies to

Converts the span representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Parameters

A character span that contains the string representation of the number to convert.

Returns

Remarks

Applies to

TryParse(String, NumberStyles, IFormatProvider, Double)

Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

Parameters

A string containing a number to convert.

Returns

Exceptions

style is not a NumberStyles value.

style includes the AllowHexSpecifier value.

Examples

The following example demonstrates the use of the Double.TryParse(String, NumberStyles, IFormatProvider, Double) method to parse the string representation of numbers that have a particular style and are formatted using the conventions of a particular culture.

Remarks

The TryParse method is like the Parse(String, NumberStyles, IFormatProvider) method, except this method does not throw an exception if the conversion fails. If the conversion succeeds, the return value is true and the result parameter is set to the outcome of the conversion. If the conversion fails, the return value is false and the result parameter is set to zero. This eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.

The style parameter defines the allowable format of the s parameter for the parse operation to succeed. It must be a combination of bit flags from the NumberStyles enumeration. The following NumberStyles members are not supported:

Elements in square brackets ([ and ]) are optional. The following table describes each element.

ElementDescription
wsOptional white space. White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag. It can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$A culture-specific currency symbol. Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern or NumberFormatInfo.CurrencyPositivePattern properties of the NumberFormatInfo object returned by the IFormatProvider.GetFormat method of the provider parameter. The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
signAn optional sign. The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
integral-digitsA series of digits ranging from 0 to 9 that specify the integral part of the number. Integral-digits can be absent if there are fractional-digits.
,A culture-specific thousands separator symbol. The current culture’s thousands separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag.
.A culture-specific decimal point symbol. The current culture’s decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional-digitsA series of digits ranging from 0 to 9 that specify the fractional part of the number. Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
eThe e or E character, which indicates that s can represent a number using exponential notation. The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential-digitsA series of digits ranging from 0 to 9 that specify an exponent.

Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

The provider parameter is a IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. The provider parameter supplies culture-specific information used in parsing. If provider is null or a NumberFormatInfo object cannot be obtained, the format information for the current culture is used.

The conversion fails if the s parameter is null or not a numeric value, the provider parameter does not yield a NumberFormatInfo object, or the style parameter is not a combination of bit flags from the NumberStyles enumeration.

If a separator is encountered in the s parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

Источник

Double. Parse Method

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Converts the string representation of a number to its double-precision floating-point number equivalent.

Overloads

Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

Converts the string representation of a number in a specified culture-specific format to its double-precision floating-point number equivalent.

Converts a character span that contains the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

Converts the string representation of a number to its double-precision floating-point number equivalent.

Converts the string representation of a number in a specified style to its double-precision floating-point number equivalent.

Remarks

Parse(String, NumberStyles, IFormatProvider)

Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

Parameters

A string that contains a number to convert.

Returns

Exceptions

s does not represent a numeric value.

style is not a NumberStyles value.

Examples

The following example illustrates the use of the Parse(String, NumberStyles, IFormatProvider) method to assign several string representations of temperature values to a Temperature object.

Remarks

The style parameter defines the style elements (such as white space, thousands separators, and currency symbols) that are allowed in the s parameter for the parse operation to succeed. It must be a combination of bit flags from the NumberStyles enumeration. The following NumberStyles members are not supported:

Elements framed in square brackets ([ and ]) are optional. The following table describes each element.

ElementDescription
wsA series of white-space characters. White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$A culture-specific currency symbol. Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern and NumberFormatInfo.CurrencyPositivePattern properties of the current culture. The current culture’s currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
signA negative sign symbol (-) or a positive sign symbol (+). The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
integral-digitsA series of digits ranging from 0 to 9 that specify the integral part of the number. The integral-digits element can be absent if the string contains the fractional-digits element.
,A culture-specific group separator. The current culture’s group separator symbol can appear in s if style includes the NumberStyles.AllowThousands flag
.A culture-specific decimal point symbol. The current culture’s decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional-digitsA series of digits ranging from 0 to 9 that specify the fractional part of the number. Fractional digits can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
EThe «e» or «E» character, which indicates that the value is represented in exponential (scientific) notation. The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential-digitsA series of digits ranging from 0 to 9 that specify an exponent.

Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

If a separator is encountered in the s parameter during a parse operation, and the applicable currency or number decimal and group separators are the same, the parse operation assumes that the separator is a decimal separator rather than a group separator. For more information about separators, see CurrencyDecimalSeparator, NumberDecimalSeparator, CurrencyGroupSeparator, and NumberGroupSeparator.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *