在Power Query中将文本格式错误地转换为数字

时间:2016-03-18 12:26:56

标签: excel powerquery m

我有一个我从商业系统下载的价格列,根据国家/地区,这些数字有不同的格式,例如:

1.260,14 -> this is seen as text by Excel
1,280.14 -> this is seen as text by Excel
1280.14  -> this is the only correct one, seen as number

我希望Power Query将所有内容转换为数字,在这种情况下,这意味着所有3个数字应该是:" 1280.14"

3 个答案:

答案 0 :(得分:1)

1)将您的列拆分为小数位:按字符数拆分列:2 - 尽可能远正确

2)第一栏:替换“。”通过“”(没有)

3)第一栏:将“,”替换为“”(无)

4)将两列合并为“。”作为分隔符并更改为十进制格式

答案 1 :(得分:1)

如果您知道哪些文档来自哪个国家/地区,则在使用Table.TransformColumnTypes时也可以考虑区域设置。您可以右键单击该列,然后选择“更改类型”使用Locale ....这将产生类似Table.TransformColumnTypes(Step, {{"Column Name", Currency.Type}}, "locale name")

的内容

答案 2 :(得分:0)

这是一个Power Query函数,我只是将混合格式文本转换为数字。它将点或逗号的最后一次出现视为小数分隔符,只要该字符在文本中只出现一次。

要使用此功能,请转到“Power Query”功能区选项卡,单击“From Other Sources”> “空白查询”。然后转到“高级编辑器”并将下面的脚本复制粘贴到编辑器并保存。然后,您可以返回主查询并点击“添加列”> “添加自定义列”。 “=”之后的公式为:toNumber([column name])

let

     toNumber = (text) =>

let

//remove characters that occur more than once as they can't be decimal separators
       text1 = if List.Count(Text.PositionOf(text, ",", Occurrence.All)) > 1
         then Text.Replace(text, ",", "") else text
,      text2 = if List.Count(Text.PositionOf(text1, ".", Occurrence.All)) > 1
         then Text.Replace(text1, ".", "") else text1

//if there are still more than one potential decimal separator, remove the kind that occurs first
//let's assume the last one is the actual decimal separator
,      text3 = if List.Count(Text.PositionOfAny(text2, {",","."}, Occurrence.All)) > 1
         then Text.Replace(text2, Text.At(text2, Text.PositionOfAny(text2, {",","."}, Occurrence.First)), "") 
         else text2

//cast as number (try different decimal separators)
,      number = 
  try       Number.ToText(Number.From(Text.Replace(text3,",","."))) 
  otherwise Number.ToText(Number.From(Text.Replace(text3,".",","))) 

in

      number
in
    toNumber