Round error value to appropriate significant figures

Average rating
(1 vote)

Function to correctly round error values to appropriate significant figures.

If first significant figure is "1", the value is rounded to the next digit.
If first significant figure is different from "1", the value is rounded to this digit.

Some Examples:

0.00125 --> 0.0013
1.2 --> 1.2
0.35 --> 0.4
0.4 --> 0.4

// Function to determine significant figures
Function Sig_Fig(V_Error)
	Variable V_Error
	Variable V_Result
	print "V_Error: "+num2str(V_Error)
	String S_Error
	String S_Result
	// Calculate power of 10 of Value
	Variable V_Error_p10 = (floor(log(abs(V_Error))))
	print "V_Value_p10: "+num2str(V_Error_p10)
	Variable V_Value
	V_Value = V_Error/(10^(V_Error_p10))
	print "V_Value_SF: "+num2str(V_Value) // Convert number to the style "x.xx" 
	// Convert this to a string
	S_Error = num2str(V_Value)
	print S_Error
	// Now check whether first character in string is a 1
	String first_char = S_Error [0]
	print first_char
	if((cmpstr(first_char,"1")==0))
		// If "1", round to the next significant number:
		S_Result = first_char+S_Error [1]+S_Error [2]+S_Error [3] // "1.23"
		V_Result = (round(str2num(S_Result)*10))/10
	else
		// If other than "1", round to this significant number:
		S_Result = first_char+S_Error [1]+S_Error [2] // "2.3"
		V_Result = round(str2num(S_Result))
	endif
	// Reconstruct value by using original power of ten:
	V_Result = V_Result*(10^(V_Error_p10))
	print V_Result
	return V_Result
End

Back to top