wpf 如何在 XAML 中格式化双精度值以在没有科学表示的情况下在末尾删除零?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16959941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:56:36  来源:igfitidea点击:

How to format double value in XAML to remove zeros at the end, without scientific representation?

c#wpfxamllistviewstring-formatting

提问by as74

I need to show double values like: 0.00008 in ListView. Unfortunatelly very often values are represented as exponential/scientific: 1E-8. I don't want users to see 1E-8 type values. I don't know and don't want to know decimal points precision of used doubles. I can't round doubles. I can solve this using c#:

我需要在 ListView 中显示双值,例如:0.00008。不幸的是,值经常被表示为指数/科学:1E-8。我不希望用户看到 1E-8 类型的值。我不知道也不想知道使用过的双精度数的小数点精度。我不能打双打。我可以使用 c# 解决这个问题:

string s = doubleValue.ToString("0.####################");  // gives what I need: 0,00008

How to do exactly same formatting using xaml?

如何使用 xaml 进行完全相同的格式化?

<ListView.View>
  <GridView AllowsColumnReorder="False">
    <GridView.Columns>
     <GridViewColumn.CellTemplate>
        <DataTemplate>
            <Border>
                <Grid>
                    <TextBlock x:Name="textBlock1" Text="{Binding Path=Profit, StringFormat={{???}}" TextTrimming="CharacterEllipsis"  />
                </Grid>
            </Border>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
  </GridView.Columns>
 </GridView>
</ListView.View>

Or how to do it using c# to assign such formatting to textBlock1 in code behind?

或者如何使用c#在后面的代码中将这种格式分配给textBlock1?

回答by Viv

<TextBlock x:Name="textBlock1"
            Text="{Binding Path=Profit,
                          StringFormat={}{0:0.####################}}"
            TextTrimming="CharacterEllipsis" />

回答by Edmund Covington

In many cases the reason that you are getting these figures is because you should actually be using decimals rather than doubles. If you do calculations with doubles, you often get tiny decimal errors which can be easily avoided.

在许多情况下,您得到这些数字的原因是您实际上应该使用小数而不是双精度数。如果您使用双精度进行计算,您经常会遇到很小的十进制错误,而这些错误很容易避免。

回答by sim1

Try this:

尝试这个:

Text="{Binding Profit, StringFormat='0.00000'}"

回答by Ned Stoyanov

Try using something like StringFormat=F6, that will format your number to 6 decimal places

尝试使用 StringFormat=F6 之类的东西,它将您的数字格式化为 6 位小数