react-native-windows icon indicating copy to clipboard operation
react-native-windows copied to clipboard

Using percent style with a decimal value (e.g. '7.8%') throws 'FormatException" in some locales

Open pre10der89 opened this issue 8 years ago • 1 comments

Environment

  1. react-native -v: react-native-cli: 2.0.1 react-native: 0.55.4
  2. npm ls rnpm-plugin-windows:
  3. npm ls react-native-windows:
  4. node -v: v7.4.0
  5. npm -v: 4.0.5
  6. yarn --version: 0.27.5

Then, specify:

  • Target Platform: UWP, WPF
  • Target Platform Version(s): .NET 4.5.1, .NET 4.6
  • Target Device(s): Desktop
  • Development Operating System: Windows 10, Windows 7
  • Visual Studio Version: 2015, 2017

Steps to Reproduce

  1. Set Operating System to a Locale that uses a comma in decimal number format
  2. Use a percent style with a fractional value

const styles = StyleSheet.create({ welcome: { fontSize: 20, textAlign: 'center', margin: '7.8%' } });

  1. Run the application

Expected Behavior

Application should not cause a FormatException and should apply the percentage value appropriately.

Actual Behavior

When using the percent mechanism in a style where the value is a decimal (e.g. '7.8%') a FormatException will be thrown if the application is running in a locale/culture where the culture's decimal format is defined as ,. In locales such as France, Germany, and Finland decimals are written with a comma; 3,14.

The FormatException happens in LayoutShadowNode.cs in the method:

YogaValue ToYogaValue(JValue value).

in the code:

if (s.EndsWith("%")) { return YogaValue.Percent(float.Parse(s.Substring(0, s.Length - 1))); }

The float.Parse method is called without specifying an IFormatProvider, which will cause .NET to use the current locale (e.g. France, Germany, Finland) for the parsing. Those versions of the float.Parse method expect a comma instead of a period. Since the declarative language uses a period for this value a FormatException will occur.

The solution is to declare that an invariant culture conversion to be used for the parsing...

return YogaValue.Percent(float.Parse(s.Substring(0, s.Length - 1), CultureInfo.InvariantCulture));

Reproducible Demo

ReactNative Example

index.windows.js.txt

C# Example

Program.cs.txt

pre10der89 avatar May 31 '18 23:05 pre10der89

@pre10der89 closing since your PR was merged.

rozele avatar Jun 04 '18 17:06 rozele