How to get excel to display a certain number of significant figures?

前端 未结 10 1228
太阳男子
太阳男子 2021-01-05 04:10

I am using excel and i want to display a value to a certain number of significant figures.

I tried using the following equation

=ROUND(value,sigfigs-         


        
10条回答
  •  执笔经年
    2021-01-05 04:29

    The formula (A2 contains the value and B2 sigfigs)

    =ROUND(A2/10^(INT(LOG10(A2))+1),B2)*10^(INT(LOG10(A2))+1)
    

    may give you the number you want, say, in C2. But if the last digit is zero, then it will not be shown with a General format. You have then to apply a number format specific for that combination (value,sigfigs), and that is via VBA. The following should work. You have to pass three parameters (val,sigd,trg), trg is the target cell to format, where you already have the number you want.

    Sub fmt(val As Range, sigd As Range, trg As Range)
        Dim fmtstr As String, fmtstrfrac As String
        Dim nint As Integer, nfrac As Integer
        nint = Int(Log(val) / Log(10)) + 1
        nfrac = sigd - nint
        If (sigd - nint) > 0 Then
          'fmtstrfrac = "." & WorksheetFunction.Rept("0", nfrac)
          fmtstrfrac = "." & String(nfrac, "0")
        Else
          fmtstrfrac = ""
        End If
        'fmtstr = WorksheetFunction.Rept("0", nint) & fmtstrfrac
        fmtstr = String(nint, "0") & fmtstrfrac
        trg.NumberFormat = fmtstr
    End Sub
    

    If you don't mind having a string instead of a number, then you can get the format string (in, say, D2) as

    =REPT("0",INT(LOG10(A2))+1)&IF(B2-(INT(LOG10(A2))+1)>0,"."&REPT("0",B2-(INT(LOG10(A2))+1)),"")
    

    (this replicates the VBA code) and then use (in, say, E2)

    =TEXT(C2,D2).
    

    where cell C2 still has the formula above. You may use cell E2 for visualization purposes, and the number obtained in C2 for other math, if needed.

提交回复
热议问题