c# - Number with decimal separator incorrectly cast to Double -
i'm experiencing weird behavior when converting number double, when using culture information.
when converting "3,3"
using dutch culture, handled correctly. if convert "3,3"
using culture, returns 33
. expecting error. see example:
static void main(string[] args) { cultureinfo culturedutch = new cultureinfo("nl-nl"); cultureinfo cultureus = new cultureinfo("en-us"); system.threading.thread.currentthread.currentculture = culturedutch; console.writeline("input 3,3 --> expected 3,3"); console.writeline("output = " + convert.todouble("3,3", culturedutch)); // actual result --> 3,3 console.writeline("input 3,3 --> expected invalidcastexception"); console.writeline("output = " + convert.todouble("3,3", cultureus)); // actual result --> 33 console.writeline(); console.writeline(); system.threading.thread.currentthread.currentculture = cultureus; console.writeline("input 3.3 --> expected invalidcastexception"); console.writeline("output = " + convert.todouble("3.3", culturedutch)); // actual result --> 33 console.writeline("input 3.3 --> expected 3.3"); console.writeline("output = " + convert.todouble("3.3", cultureus)); // actual result --> 3.3 console.readline(); }
what correct way handle this? prefer exception when decimal (or thousand) separator invalid.
if want parse use dedicated parse methods in can set numberstyles
the following code throw formatexception
var culture =new cultureinfo("en-us"); var result = double.parse("3,3", numberstyles.allowdecimalpoint, culture);
for further information see double.parse method
Comments
Post a Comment