1

我有一个网页,它从数据库中获取数据,然后在线显示它,但由于某种原因,如果值是0.4它正在改变它0.400000005960464,如果它是859.8它改变它859.799987792969。我对其进行了调试,发现它正在从数据库中正确读取值,所以这不是问题,而是.aspx页面弄乱了这些值。这就是我为该页面所拥有的,正在更改的是 DataField 组件 1 和 2。

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" 
AutoEventWireup="true" CodeFile="TestData.aspx.cs" 
Inherits="Inventory_TestData" Title="Module Test Data" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" 
Runat="Server">
<ul>
    <li>Item ID:
        <asp:TextBox ID="txtItem" runat="server" AutoPostBack="True" OnTextChanged="txtItem_TextChanged"></asp:TextBox></li></ul>
<li style="text-align: left"><span style="color: #009999">Test Data:</span><asp:ObjectDataSource
    ID="dsrcGetTestData" runat="server" SelectMethod="getTestData" TypeName="TestDataReader" DeleteMethod="deleteData">
    <SelectParameters>
        <asp:QueryStringParameter DefaultValue="0" Name="nItemID" QueryStringField="Item" Type="Int32" />
    </SelectParameters>
    <DeleteParameters>
        <asp:Parameter DefaultValue="" Name="TestID" Type="Int32" />
        <asp:Parameter DefaultValue="0" Name="TestType" Type="Object" />
    </DeleteParameters>
</asp:ObjectDataSource>
    <asp:GridView ID="gvTestItem" runat="server" AutoGenerateColumns="False" BackColor="White"
        BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4"
        DataSourceID="dsrcGetTestData" Font-Size="0.65em" ForeColor="Black" GridLines="Vertical" DataKeyNames="TestID">
        <FooterStyle BackColor="#CCCC99" />
        <Columns>
            <asp:CommandField ShowDeleteButton="True" />

             <asp:BoundField DataField="Component1" HeaderText="Component1" SortExpression="Component1"   />    
             <asp:BoundField DataField="Component2" HeaderText="Component2" SortExpression="Component2"/>    

        </Columns>
        <RowStyle BackColor="#F7F7DE" />
        <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right"  />
        <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White"  />
    </asp:GridView>

 </asp:Content>
4

2 回答 2

0

您的问题可能是由于浮点数被存储为数字的近似值。为了解决这个问题,您可以使用固定精度的十进制类型,或者在使用浮点数之前将它们转换为固定精度的十进制类型。

浮点数一般没有精确的二进制表示。... 当浮点数从一种表示形式转换为另一种表示形式时,该数字的最低有效位可能会略有不同。当数字从一种类型转换为另一种类型时,通常会发生转换......当格式化为字符串时,数字可能不会显示预期值。

为了最大限度地减少这些影响,您应该使用可用的数字类型之间最接近的匹配。例如,如果您正在使用 SQL Server,如果您将一个实数类型的 Transact-SQL 值转换为一个浮点类型的值,则确切的数值可能会发生变化。在 .NET Framework 中,将 Single 转换为 Double 也可能会产生意外结果。在这两种情况下,一个好的策略是让应用程序中的所有值都使用相同的数字类型。

根据MSDN 中的浮点数。

于 2014-01-09T20:31:03.783 回答
0

您可以尝试将格式字符串添加到列中。例如以下

<asp:BoundField DataFormatString="{0:F3}" DataField="Component1" HeaderText="Component1" SortExpression="Component1" />    
<asp:BoundField DataFormatString="{0:F3}" DataField="Component2" HeaderText="Component2" SortExpression="Component2"/>

将数字限制为小数点后 3 位。

于 2014-01-09T20:31:07.543 回答