Excel - Deleting zeros on the right side of the cells - excel

I would like to delete the zeros on the right side of the cells if there are more then 3 zeros.
Example:
A B
12345 12345
1230 1230
12345600 12345600
12000 12000
12340000000000000 1234000
1234500000000000000000 12345000
Is it possible to excel using just formula in the cells of the column B??
How to do?
Thanks so much!

The answers, given until now, are treating the numbers as strings, while I'd go for the numeric approach:
if mod(number,10000) = 0
then number = number div 1000;
return number;
Which means: if the number, divided by 10,000 equals 0 (if the number ends with '0000') then return the number, divided by a thousand (remove the last three zeroes).
You don't need this one time, but you need to remove all triplets of three zeroes, as much as possible, so instead of a simple if-loop, you might go for a while-loop:
while mod(number,10000) = 0
do number = number div 1000;
return number;
You can use this in a VBA function:
Public Function remove_ending_blanks(r As Range) As Double
Dim temp As Double
temp = r.Value
While temp Mod 10000 = 0
temp = temp / 1000
Wend
remove_ending_blanks = temp
End Function
You might also do this, using a formula, but the while-loop will need to be done using a circular reference, which is quite tricky.

Try this shorter formula solution and worked in left max. 3 zeros on the right side.
In B1, formula copied down :
=0+TRIM(LEFT(A1,MATCH(9^9,INDEX(1/MID(A1,ROW($1:$99),1),0))+3))

Bit of a stretch (I'm prety sure it can be done better), but if you have access to TEXTJOIN, try the following in B2:
=IF(RIGHT(A1,4)="0000",FILTERXML("<t><s>"&TEXTJOIN("</s><s>",1,MID(A1,1,LEN(A1)-ROW(A$1:INDEX(A:A,LEN(A1)))))&"</s></t>","//s[substring(., string-length(.)-3) != 0]"),A1)
Or:
=IF(RIGHT(A7,4)="0000",LEFT(A7,MAX((MID(A7,ROW(A$1:INDEX(A:A,LEN(A7))),1)<>"0")*(ROW(A$1:INDEX(A:A,LEN(A7)))))+3),A7)
Note: It's an array formula and needs to be confirmed through CtrlShiftEnter
It looks frightening, agreed, but would yield the correct result as far as my testing went. For example 100000400000 would yield 1000004000.

you could use this formula
=IF(RIGHT(A1,4)="0000",LEFT(A1,LEN(A1/10^LEN(A1))-FIND(".",A1/10^LEN(A1))+3),A1)

Consider:
Public Function ZeroTrimmer(r As Range) As String
s = r.Text
While Right(s, 4) = "0000"
s = Left(s, Len(s) - 1)
Wend
ZeroTrimmer = s
End Function

Edit: These will give incorrect results. I mis-read the question and didn't realize you wanted to leave a max of 3 trailing zeroes. The below will remove all trailing zeroes.
If it's an unknown number of trailing zeroes, it gets tricky. You'd have to use something like this...
=(10^(LEN(RIGHT(VALUE(CONCATENATE("0.", A2)),LEN(VALUE(CONCATENATE("0.", A2)))-FIND(".",VALUE(CONCATENATE("0.", A2)))))))*VALUE(CONCATENATE("0.", A2))
If you know the number of trailing zeroes it becomes much easier, and can be done like this:
=LEFT(A2,LEN(A2)-3)
Where 3 in the above formula represents the number of trailing zeroes to remove. Another variation could be:
=A2/(10^3)
These formulas will work if text or numeric.

Related

EXCEL: Unique alphanumeric code with certain characters excluded (without VBA / duplicates)

I am trying to create a list =5 alphanumeric characters.
They cannot contain 1, and i and there cannot be duplicates when dragging / copying the code down.
The characters that are allowed are:
023456789ABCDEFGHJKLMNOPQRSTUWVXYZ (Capital)
I have tried numerous of options but I can't seem to figure this one out.
Cheers
If your allowable character string is in cell A1 then the following formula will result in random codes that are each five characters in length:
=MID(A1,RANDBETWEEN(1,34),1) & MID(A1,RANDBETWEEN(1,34),1) & MID(A1,RANDBETWEEN(1,34),1) & MID(A1,RANDBETWEEN(1,34),1) & MID(A1,RANDBETWEEN(1,34),1)
But note that there is no guarantee that the codes will be unique.
As #ScottCraner pointed out... if you should happen to have Office 365, you can use this much shorter formula that takes advantage of two new functions only available in Excel 365:
=CONCAT(MID(A1,RANDARRAY(5,,1,34,TRUE),1))
But again, there is no guarantee that the resulting codes will be unique.
This formula will generate the codes in order
=SUBSTITUTE(SUBSTITUTE(BASE(K, 34,5),"1","Z"),"I","Y")
Here K can be 0, 1, 2, .... One way to generate the first ~1,048,576 K's is to use ROW()-1. You could get higher values of K by using something like K = 1048576*(COLUMN()-1) + ROW()-1.
The formula works by
(a) calling BASE(K, 34, 5) to get a 5-char long base-34 representation of K
(b) substituting Z for 1 since 1 is not a valid char
(c) substituting Y for I since I is not a valid char

How do I sum data based on a PART of the headers name?

Say I have columns
/670 - White | /650 - black | /680 - Red | /800 - Whitest
These have data in their rows. Basically, I want to SUM their values together if their headers contain my desired string.
For modularity's sake, I wanted to merely specify to sum /670, /650, and /680 without having to mention the rest of the header text.
So, something like =SUMIF(a1:c1; "/NUM & /NUM & /NUM"; a2:c2)
That doesn't work, and honestly I don't know what i should be looking for.
Additional stuff:
I'm trying to think of the answer myself, is it possible to mention the header text as condition for ifs? Like: if A2="/650 - Black" then proceed to sum the next header. Is this possible?
Possibility it would not involve VBA, a draggable formula would be preferable!
At this point, I may as well request a version which handles the complete header name rather than just a part of it as I believe it to be difficult for formula code alone.
Thanks for having a look!
Let me know if I need to elaborate.
EDIT: In regards to data samples, any positive number will do actually, damn shame stack overflow doesn't support table markdown. Anyway, for example then..:
+-------------+-------------+-------------+-------------+-------------+
| A | B | C | D | E |
+---+-------------+-------------+-------------+-------------+-------------+
| 1 |/650 - Black |/670 - White |/800 - White |/680 - Red |/650 - Black |
+---+-------------+-------------+-------------+-------------+-------------+
| 2 | 250 | 400 | 100 | 300 | 125 |
+---+-------------+-------------+-------------+-------------+-------------+
I should have clarified:
The number range for these headers would go from /100 - /9999 and no more than that.
EDIT:
Progress so far:
https://docs.google.com/spreadsheets/d/1GiJKFcPWzG5bDsNt93eG7WS_M5uuVk9cvkt2VGSbpxY/edit?usp=sharing
Formula:
=SUMPRODUCT((A2:D2*
(MID($A$1:$D$1,2,4)=IF(LEN($H$1)=4,$H$1&"",$H$1&" ")))+(A2:D2*
(MID($A$1:$D$1,2,4)=IF(LEN($I$1)=4,$I$1&"",$I$1&" ")))+(A2:D2*
(MID($A$1:$D$1,2,4)=IF(LEN($J$1)=4,$J$1&"",$J$1&" "))))
Apparently, each MID function is returning false with each F9 calculation.
EDIT EDIT:
Okay! I found my issue, it's the /being read when you ALSO mentioned that it wasn't required. Man, I should stop skimming!
Final Edit:
=SUMPRODUCT((RETURNSUM*
(MID(HEADER,2,4)=IF(LEN(Match5)=4,Match5&"",Match5&" ")))+(RETURNSUM*
(MID(HEADER,2,4)=IF(LEN(Match6)=4,Match6&"",Match6&" ")))+(RETURNSUM*
(MID(HEADER,2,4)=IF(LEN(Match7)=4,Match7&"",Match7&" ")))
The idea is that Header and RETURNSUM will become match criteria like the matches written above, that way it would be easier to punch new criterion into the search table. As of the moment, it doesn't support multiple rows/dragging.
I have knocked up a couple of formulas that will achieve what you are looking for. For ease I have made the search input require the number only as pressing / does not automatically type into the formula bar. I apologise for the length of the answer, I got a little carried away with the explanation.
I have set this up for 3 criteria located in J1, K1 and L1.
Here is the output I achieved:
Formula 1 - SUMPRODUCT():
=SUMPRODUCT((A4:G4*(MID($A$1:$G$1,2,4)=IF(LEN($J$1)=4,$J$1&"",$J$1&" ")))+(A4:G4*(MID($A$1:$G$1,2,4)=IF(LEN($K$1)=4,$K$1&"",$K$1&" ")))+(A4:G4*(MID($A$1:$G$1,2,4)=IF(LEN($L$1)=4,$L$1&"",$L$1&" "))))
Sumproduct(array1,[array2]) behaves as an array formula without needed to be entered as one. Array formulas break down ranges and calculate them cell by cell (in this example we are using single rows so the formula will assess columns seperately).
(A4:G4*(MID($A$1:$G$1,2,4)=IF(LEN($J$1)=4,$J$1&"",$J$1&" ")))
Essentially I have broken the Sumproduct() formula into 3 identical parts - 1 for each search condition. (A4:G4*: Now, as the formula behaves like an array, we will multiply each individual cell by either 1 or 0 and add the results together.
1 is produced when the next part of the formula is true and 0 for when it is false (default numeric values for TRUE/FALSE).
(MID($A$1:$G$1,2,4)=IF(LEN($J$1)=4,$J$1&"",$J$1&" "))
MID(text,start_num,num_chars) is being used here to assess the 4 digits after the "/" and see whether they match with the number in the 3 cells that we are searching from (in this case the first one: J1). Again, as SUMPRODUCT() works very much like an array formula, each cell in the range will be assessed individually.
I have then used the IF(logical_test,[value_if_true],[value_if_false]) to check the length of the number that I am searching. As we are searching for a 4 digit text string, if the number is 4 digits then add nothing ("") to force it to a text string and if it is not (as it will have to be 3 digits) add 1 space to the end (" ") again forcing it to become a text string.
The formula will then perform the calculation like so:
The MID() formula produces the array: {"650 ","670 ","800 ","680 ","977 ","9999","143 "}. This combined with the first search produces {TRUE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE} which when multiplied by A4:G4
(remember 0 for false and 1 for true) produces this array: {250,0,0,0,0,0,0} essentially pulling the desired result ready to be summed together.
Formula 2: =SUM(IF(Array)): [This formula does not work for 3 digit numbers as they will exist within the 4 digit numbers! I have included it for educational purposes only]
=SUM(IF(ISNUMBER(SEARCH($J$1,$A$1:$G$1)),A8:G8),IF(ISNUMBER(SEARCH($K$1,$A$1:$G$1)),A8:G8),IF(ISNUMBER(SEARCH($L$1,$A$1:$G$1)),A8:G8))
The formula will need to be entered as an array (once copy and pasted while still in the formula bar hit CTRL+SHIFT+ENTER)
This formula works in a similar way, SUM() will add together the array values produced where IF(ISNUMBER(SEARCH() columns match the result column.
SEARCH() will return a number when it finds the exact characters in a cell which represents it's position in number of characters. By using ISNUMBER() I am avoiding having to do the whole MID() and IF(LEN()=4,""," ") I used in the previous formula as TRUE/FALSE will be produced when a match is found regardless of it's position or cell formatting.
As previously mentioned, this poses a problem as 999 can be found within 9999 etc.
The resulting array for the first part is: {250,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE} (if you would like to see the array you can highlight that part of the formula and calculate with F9 but be sure to highlight the exact brackets for that part of the formula).
I hope I have explained this well, feel free to ask any questions about stuff that you don't understand. It is good to see people keen to learn and not just fishing for a fast answer. I would be more than happy to help and explain in more depth.
I start this solution with the names in an array, you can read the header names into an array with not too much difficulty.
Sub test()
Dim myArray(1 To 4) As String
myArray(1) = "/670 - White"
myArray(2) = "/650 - black"
myArray(3) = "/680 - Red"
myArray(4) = "/800 - Whitest"
For Each ArrayValue In myArray
'Find position of last character
endposition = InStr(1, ArrayValue, " - ", vbTextCompare)
'Grab the number section from the string, based on starting and ending positions
stringvalue = Mid(ArrayValue, 2, endposition - 2)
'Convert to number
NumberValue = CLng(stringvalue)
'Add to total
Total = Total + NumberValue
Next ArrayValue
'Print total
Debug.Print Total
End Sub
This will print the answer to the debug window.

How would I remove all leading alphabetical characters?

I am interested in removing leading alphabetical (alpha) characters from cells which appear in a column. I only wish to remove the leading alpha characters (including UPPER and LOWER case): if alpha characters appear after a number they should be kept. Some cells in the column might not have leading alpha characters.
Here is an example of what I have:
36173
PIL51014
4UNV22001
ZEB54010
BICMPAFG11BK
BICMPF11
Notice how there are not always the same number of leading alpha characters. I cannot simply use a Left or Right function in Excel, because the number of characters I wish to keep and remove varies.
A correct output for what I am looking for would look like:
36173
51014
4UNV22001
54010
11BK
11
Notice how the second to last row preserved the characters "BK", and the 3rd row preserved "UNV". I cannot simply remove all alpha characters.
I am a beginner with visual basic and was not able to figure out how to use excel functions to address my issue. How would I do this?
Here is an Excel formula that will "strip off the leading alpha characters" Actually, it looks for the first numeric character, and returns everything after that:
=MID(A1,MIN(FIND({0;1;2;3;4;5;6;7;8;9},A1&"0123456789")),99)
The 99 at the end needs to be some value longer than the longest string you might be processing. 99 usually works.
Here's a formula based solution complete with test results:
=MID(A1,MIN(SEARCH({0,1,2,3,4,5,6,7,8,9},A1&"0123456789"),255),100)
Change the 100 at the end if any string may be longer than 100 characters. Also the 255 is not needed, but it won't hurt.
This short UDF should strip off leading alphabetic characters.
Function noLeadAlpha(str As String)
If Not IsNumeric(str) Then
Do While Asc(str) < 48 Or Asc(str) > 57
str = Mid(str, 2)
If Not CBool(Len(str)) Then Exit Do
Loop
End If
noLeadAlpha = str
End Function
        
Koodos Jeeped, you beat me to it.
But here is an alternative anyway:
Function RemoveAlpha(aString As String) As String
For i = 1 To Len(aString)
Select Case Mid(aString, i, 1)
Case "0" To "9"
RemoveAlpha = Right(aString, Len(aString) - i + 1): Exit For
End Select
Next i
End Function

Excel: complicated SUMPRODUCT formula needed

I'm in search of a SUMPRODUCT formula, or a similar sort of formula which does the same thing. It should do the following:
On worksheet A it needs to ignore incorrect zipcodes, meaning
zipcodes which do not consist of 4 numbers and 2 letters need to be
ignored. It also needs to take into account that there sometimes are
superfluous spaces behind the zipcode. And sometimes there is a
space between the numbers and letters, sometimes there isn't. Just
the 4 numbers and 2 letters need to be compared.
The correct zipcodes on worksheet A need to be compared with the
zipcodes on worksheet B. If they match, then all the values behind
the zip code need to be summed up. If there is another record
starting with the same zipcode then these need to be added up as
well.
Neither of the worksheets should need to be changed, since the data is generated frequently. The formula should be able to work on a third, separate worksheet. And it should work in Excel 2003.
EDIT: Added point 3.
I'll add an image to visualize what I mean. Hopefully someone can help me!
With some helper columns, you could use something like this (open in new tab for larger version):
The formulae:
In B2 to remove spaces and hence get a 'clean' ZIP and check the length:
=IF(LEN(SUBSTITUTE(A2," ",""))=6,SUBSTITUTE(A2," ",""),"")
In C2, to get the sum:
=IFERROR(IF(AND(ISNUMBER(LEFT(B2,4)*1),CODE(MID(LOWER(B2),5,1))>=97,CODE(MID(LOWER(B2),5,1))<=122,CODE(RIGHT(LOWER(B2)))>=97,CODE(RIGHT(LOWER(B2)))<=122),SUMPRODUCT($H$2:$K$8*($G$2:$G$8=B2)),""),"")
In G2, I used the same one as in B2:
=IF(LEN(SUBSTITUTE(F2," ",""))=6,SUBSTITUTE(F2," ",""),"")
Without the helper, the formula becomes much longer because of repeating parts:
=IFERROR(IF(AND(LEN(SUBSTITUTE(A2," ",""))=6,ISNUMBER(LEFT(SUBSTITUTE(A2," ",""),4)*1),CODE(MID(LOWER(SUBSTITUTE(A2," ","")),5,1))>=97,CODE(MID(LOWER(SUBSTITUTE(A2," ","")),5,1))<=122,CODE(RIGHT(LOWER(SUBSTITUTE(A2," ",""))))>=97,CODE(RIGHT(LOWER(SUBSTITUTE(A2," ",""))))<=122),SUMPRODUCT($H$2:$K$8*(SUBSTITUTE($F$2:$F$8," ","")=SUBSTITUTE(A2," ",""))),""),"")
Or
=IFERROR(
IF(
AND(
LEN(SUBSTITUTE(A2," ",""))=6, ' Check length
ISNUMBER(LEFT(SUBSTITUTE(A2," ",""),4)*1), ' Check numbers
CODE(MID(LOWER(SUBSTITUTE(A2," ","")),5,1))>=97, ' Check if letter
CODE(MID(LOWER(SUBSTITUTE(A2," ","")),5,1))<=122, ' Check if letter
CODE(RIGHT(LOWER(SUBSTITUTE(A2," ",""))))>=97, ' Check if letter
CODE(RIGHT(LOWER(SUBSTITUTE(A2," ",""))))<=122 ' Check if letter
),
SUMPRODUCT(
$H$2:$K$8*
(SUBSTITUTE($F$2:$F$8," ","")=SUBSTITUTE(A2," ",""))),
""
),
""
)
Oops, forgot that IFERROR was not in 2003. The only reason why I used it was that MID would return an empty string and CODE would subsequently give an error. You can use the below instead which makes sure the string is 6 chars first:
=IF(LEN(SUBSTITUTE(A2," ",""))=6,IF(AND(ISNUMBER(LEFT(SUBSTITUTE(A2," ",""),4)*1),CODE(MID(LOWER(SUBSTITUTE(A2," ","")),5,1))>=97,CODE(MID(LOWER(SUBSTITUTE(A2," ","")),5,1))<=122,CODE(RIGHT(LOWER(SUBSTITUTE(A2," ",""))))>=97,CODE(RIGHT(LOWER(SUBSTITUTE(A2," ",""))))<=122),SUMPRODUCT($H$2:$K$8*(SUBSTITUTE($F$2:$F$8," ","")=SUBSTITUTE(A2," ",""))),""),"")
Here you have a formula to validate Dutch postal codes
=AND(LEN(A2)=6; ISNUMBER(VALUE(LEFT(A2;4))); CODE(MID(LOWER(A2);5;1)) >= 97; CODE(MID(LOWER(A2);5;1)) <= 122; CODE(MID(LOWER(A2);6;1)) >= 97; CODE(MID(LOWER(A2);6;1)) <= 122)
0-9 = ASCII code 48 to 57
a-z = ASCII code 97 to 122 (lowercase)
In case you have a Dutch version of Excel, the formula would be:
=EN(LENGTE(A2)=6; ISGETAL(WAARDE(LINKS(A2;4))); CODE(DEEL(KLEINE.LETTERS(A2);5;1)) >= 97; CODE(DEEL(KLEINE.LETTERS(A2);5;1)) <= 122; CODE(DEEL(KLEINE.LETTERS(A2);6;1)) >= 97; CODE(DEEL(KLEINE.LETTERS(A2);6;1)) <= 122)

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

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-1-INT(LOG10(ABS(value))))
with value replaced by the number I am using and sigfigs replaced with the number of significant figures I want.
This formula works sometimes, but other times it doesn't.
For instance, the value 18.036, will change to 18, which has 2 significant figures. The way around this is to change the source formatting to retain 1 decimal place. But that can introduce an extra significant figure. For instance, if the result was 182 and then the decimal place made it change to 182.0, now I would have 4 sig figs instead of 3.
How do I get excel to set the number of sig figs for me so I don't have to figure it out manually?
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.
WARNING: crazy-long excel formula ahead
I was also looking to work with significant figures and I was unable to use VBA as the spreadsheets can't support them. I went to this question/answer and many other sites but all the answers don't seem to deal with all numbers all the time. I was interested in the accepted answer and it got close but as soon as my numbers were < 0.1 I got a #value! error. I'm sure I could have fixed it but I was already down a path and just pressed on.
Problem:
I needed to report a variable number of significant figures in positive and negative mode with numbers from 10^-5 to 10^5. Also, according to the client (and to purple math), if a value of 100 was supplied and was accurate to +/- 1 and we wish to present with 3 sig figs the answer should be '100.' so I included that as well.
Solution:
My solution is for an excel formula that returns the text value with required significant figures for positive and negative numbers.
It's long, but appears to generate the correct results according to my testing (outlined below) regardless of number and significant figures requested. I'm sure it can be simplified but that isn't currently in scope. If anyone wants to suggest a simplification, please leave me a comment!
=TEXT(IF(A1<0,"-","")&LEFT(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00"),sigfigs+1)*10^FLOOR(LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00")),1),(""&(IF(OR(AND(FLOOR(LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00")),1)+1=sigfigs,RIGHT(LEFT(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00"),sigfigs+1)*10^FLOOR(LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00")),1),1)="0"),LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00"))<=sigfigs-1),"0.","#")&REPT("0",IF(sigfigs-1-(FLOOR(LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00")),1))>0,sigfigs-1-(FLOOR(LOG10(TEXT(ABS(A1),"0."&REPT("0",sigfigs-1)&"E+00")),1)),0)))))
Note: I have a named range called "sigfigs" and my numbers start in cell A1
Test Results:
I've tested it against the wikipedia list of examples and my own examples so far in positive and negative. I've also tested with a few values that gave me issues early on and all seem to produce the correct results.
I've also tested with a few values that gave me issues early on and all seem to produce the correct results now.
3 Sig Figs Test
99.99 -> 100.
99.9 -> 99.9
100 -> 100.
101 -> 101
Notes:
Treating Negative Numbers
To Treat Negative Numbers, I have included a concatenation with a negative sign if less than 0 and use the absolute value for all other work.
Method of construction:
It was initially divided into about 6 columns in excel that performed the various steps and at the end I merged all of the steps into one formula above.
Use scientific notation, say if you have 180000 and you need 4 sigfigs the only way is to type as 1.800x10^5
I added to your formula so it also automatically displays the correct number of decimal places. In the formula below, replace the digit "2" with the number of decimal places that you want, which means you would need to make four replacements. Here is the updated formula:
=TEXT(ROUND(A1,2-1-INT(LOG10(ABS(A1)))),"0"&IF(INT(LOG10(ABS(ROUND(A1,2-1-INT(LOG10(ABS(A1)))))))<1,"."&REPT("0",2-1-INT(LOG10(ABS(ROUND(A1,2-1-INT(LOG10(ABS(A1)))))))),""))
For example, if cell A1 had the value =1/3000, which is 0.000333333.., the above formula as-written outputs 0.00033.
This is an old question, but I've modified sancho.s' VBA code so that it's a function that takes two arguments: 1) the number you want to display with appropriate sig figs (val), and 2) the number of sig figs (sigd). You can save this as an add-in function in excel for use as a normal function:
Public Function sigFig(val As Range, sigd As Range)
Dim nint As Integer
Dim nfrac As Integer
Dim raisedPower As Double
Dim roundVal As Double
Dim fmtstr As String
Dim fmtstrfrac As String
nint = Int(Log(val) / Log(10)) + 1
nfrac = sigd - nint
raisedPower = 10 ^ (nint)
roundVal = Round(val / raisedPower, sigd) * raisedPower
If (sigd - nint) > 0 Then
fmtstrfrac = "." & String(nfrac, "0")
Else
fmtstrfrac = ""
End If
If nint <= 0 Then
fmtstr = String(1, "0") & fmtstrfrac
Else
fmtstr = String(nint, "0") & fmtstrfrac
End If
sigFig = Format(roundVal, fmtstr)
End Function
It seems to work in all the use cases I've tried so far.
Rounding to significant digits is one thing... addressed above. Formatting to a specific number of digits is another... and I'll post it here for those of you trying to do what I was and ended up here (as I will likely do again in the future)...
Example to display four digits:
.
Use Home > Styles > Conditional Formatting
New Rule > Format only cells that contain
Cell Value > between > -10 > 10 > Format Number 3 decimal places
New Rule > Format only cells that contain
Cell Value > between > -100 > 100 > Format Number 2 decimal places
New Rule > Format only cells that contain
Cell Value > between > -1000 > 1000 > Format Number 1 decimal place
New Rule > Format only cells that contain
Cell Value > not between > -1000 > 1000 > Format Number 0 decimal places
.
Be sure these are in this order and check all of the "Stop If True" boxes.
The formula below works fine. The number of significant figures is set in the first text formula. 0.00 and 4 for 3sf, 0.0 and 3 for 2sf, 0.0000 and 6 for 5sf, etc.
=(LEFT((TEXT(A1,"0.00E+000")),4))*POWER(10,
(RIGHT((TEXT(A1,"0.00E+000")),4)))
The formula is valid for E+/-999, if you have a number beyond this increase the number of the last three zeros, and change the second 4 to the number of zeros +1.
Note that the values displayed are rounded to the significant figures, and should by used for display/output only. If you are doing further calcs, use the original value in A1 to avoid propagating minor errors.
As a very simple display measure, without having to use the rounding function, you can simply change the format of the number and remove 3 significant figures by adding a decimal point after the number.
I.e. #,###. would show the numbers in thousands. #,###.. shows the numbers in millions.
Hope this helps
You could try custom formatting instead.
Here's a crash course: https://support.office.com/en-nz/article/Create-a-custom-number-format-78f2a361-936b-4c03-8772-09fab54be7f4?ui=en-US&rs=en-NZ&ad=NZ.
For three significant figures, I type this in the custom type box:
[>100]##.0;[<=100]#,##0
You could try
=ROUND(value,sigfigs-(1+INT(LOG10(ABS(value)))))
value :: The number you wish to round.
sigfigs :: The number of significant figures you want to round to.

Resources