Python-四舍五入到最接近的9(最近的单位,十,一百)

时间:2019-04-03 13:29:21

标签: python rounding

您能想到Python中的函数将任何数字四舍五入到最接近的9吗?

例外情况是四舍五入到最接近的单位,十,一百,千年等。

76 --> 69 
242 --> 239 
8434 --> 8399 
34857 --> 33999
987482 --> 986999

1 个答案:

答案 0 :(得分:1)

使用以下功能:

<DataTemplate>
    <Button Content="{Binding Text}">
        <Button.Visibility>
            <MultiBinding Converter="{StaticResource ListBoxItemToVisibility}">
                <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType=ListBoxItem}"/>
                <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType=ScrollViewer}"/>
                <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType=ListBox}"/>
                <Binding Path="ActualHeight" RelativeSource="{RelativeSource FindAncestor, AncestorType=ListBoxItem}"/>
                <Binding Path="VerticalOffset" RelativeSource="{RelativeSource FindAncestor, AncestorType=ScrollViewer}"/>
                <Binding Path="ActualHeight" RelativeSource="{RelativeSource FindAncestor, AncestorType=ListBox}"/>
            </MultiBinding>
        </Button.Visibility>
    </Button>
</DataTemplate>

注1:如果最后将import math def round_to_nearest_9(number): number_of_fixed_digits = 1 factor = max(10, math.pow(10, math.floor(math.log10(number)) - number_of_fixed_digits)) return (number // factor) * factor - 1 更改为- 1,您甚至会舍入包括99美分在内的数字 注意2:少量的行为是危险的,例如19-> 9

编辑:  @MarkDickinson提出了以下修改,以处理注释2中引用的不良行为:

-0.01