python json float with leading zeros

时间:2017-12-18 07:24:11

标签: python json python-3.x

How to use python (3.5) json standard library to print floats with trailing zeros?

import json
to_be_serialized = {'something': 0.020}
print(json.dumps(to_be_serialized))
{"something": 0.02}  # desired output: {"something": 0.020}

I tried this but unfortunately without desired result.

2 个答案:

答案 0 :(得分:1)

花车并不是为了保存这类信息而设计的。 0.020和0.02相同。

但您可以手动设置小数位数:

import json
test = 0.020
print(json.dumps({'test': '{:.3f}'.format(test)}))

将打印

{"test": "0.020"}

请注意:a)现在这是一个字符串,不再是浮点数,而b){:.3f}部分专门将小数位数设置为3。

答案 1 :(得分:1)

最后我被迫使用非标准的python库BorderLayout。 (因为<Style x:Key="DefaultLanguageButtonStyle" TargetType="{x:Type Button}" > <!--BasedOn="{StaticResource DefaultButton}" >--> <Setter Property="OverridesDefaultStyle" Value="True" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Border x:Name="border" BorderThickness="0" BorderBrush="DarkGray" Background="{TemplateBinding Background}"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="border" Property="BorderBrush" Value="Black" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter Property="Effect"> <Setter.Value> <Border BorderThickness="5,5,0,0" > </Border> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="FontSize" Value="30" /> <Setter Property="FontWeight" Value="Bold" /> <Setter Property="HorizontalAlignment" Value="Center" /> <Setter Property="VerticalAlignment" Value="Center" /> <Setter Property="HorizontalContentAlignment" Value="Center" /> <Setter Property="VerticalContentAlignment" Value="Center" /> <Setter Property="Foreground" Value="{DynamicResource RedBrush}" /> <Setter Property="Background" Value="{DynamicResource WhiteBrush}" /> <Setter Property="BorderThickness" Value="{DynamicResource NoBorder}" /> <Setter Property="Height" Value="100" /> </Style> 包不支持小数)

simplejson

我无法找到使用标准json库执行此操作的方法,但至少它正在运行。