I have proved the following statement and I would like to know if my proof is correct and/or/how if it could be improved, thanks.
Suppose $f:B\to\mathbb{R}$ is a Borel measurable function. Define $g:\mathbb{R}\to\mathbb{R}$ by $g(x) =\begin{cases} f (x) & \text{ if } x\in B,\\ 0 & \text{ if } x\in\mathbb{R}\setminus B. \end{cases}$ Prove that g is a Borel measurable function.
My proof:
First note that since $f$ is a Borel measurable function and $\mathbb{R}\in\mathcal{B}$, $f^{-1}(\mathbb{R})=B\in\mathcal{B}$ and so also $\mathbb{R}\setminus B\in\mathcal{B}$.
Now, let $A\in\mathcal{B}$; we have to show that $g^{-1}(A)\in\mathcal{B}$ and there are three possible cases: $A\cap f(B)=\emptyset$ and $0\notin A$, $A\cap f(B)=\emptyset$ and $0\in A$, $A\cap f(B)\neq\emptyset$.
In the first case $g^{-1}(A)=\emptyset\in\mathcal{B}$, in the second case $g^{-1}(A)=\mathbb{R}\setminus B\in\mathcal{B}$ and in the third case $g^{-1}(A)=g^{-1}(A\cap\mathbb{R})=g^{-1}(A\cap (f(B)\cup\mathbb{R}\setminus f(B)))=g^{-1}(A\cap f(B))\cup (A\cap\mathbb{R}\setminus f(B))=g^{-1}(A\cap f(B))\cup g^{-1}(A\cap (\mathbb{R}\setminus f(B)))=f^{-1}(A\cap f(B))\cup\mathbb{R}\setminus B=(f^{-1}(A)\cap B)\cup\mathbb{R}\setminus B\in\mathcal{B}$ since $f^{-1}(A)\in\mathcal{B}$ because $A\in\mathcal{B}$ and $f$ is Borel measurable by hypothesis, and $B, \mathbb{R}\setminus B\in\mathcal{B}$.$\square$
ADDENDUM: a simpler proof, following the method illustrated by Snoop in the answer below
It suffices to show that $g^{-1}((a,\infty))\in\mathcal{B}$ for all $a\in\mathbb{R}$. So, let $a\in\mathbb{R}$: then $g^{-1}((a,\infty))=\begin{cases}f^{-1}((a,\infty)) & \text{ if }a>0\\ f^{-1}((a,\infty))\cup\mathbb{R}\setminus B & \text{ if }a\leq 0\end{cases}$. Now, $f^{-1}((a,\infty))\in\mathcal{B}$ since $(a,\infty)\in\mathcal{B}$ and $f$ is Borel measurable by hypothesis and for the same reason $f^{-1}(\mathbb{R})=B\in\mathcal{B}$ so $\mathbb{R}\setminus B\in\mathcal{B}$ thus $f^{-1}((a,\infty))\cup\mathbb{R}\setminus B\in\mathcal{B}$ too and this concludes the proof. $\square$
I will assume $B \in \mathcal{B}(\mathbb{R})$ thus $\mathbb{R}/B \in \mathcal{B}(\mathbb{R})$. Since $f$ is $\mathcal{B}(B)/\mathcal{B}(\mathbb{R})$-measurable and the measurable space is presumably $(B,\mathcal{B}(B))$, we have that $g$ is a sort of extension of $f$ to $(\mathbb{R},\mathcal{B}(\mathbb{R}))$. We have $\mathcal{B}(B)\subset \mathcal{B}(\mathbb{R})$ and $$\{g \geq c\}=\begin{cases} \{f \geq c\}\cup(\mathbb{R}/B) & c \leq 0 \\ \{f \geq c\} & c > 0 \end{cases}\in \mathcal{B}(\mathbb{R})$$ which shows that $g$ is Borel measurable because $\{f \geq c\} \in \mathcal{B}(B) \, \forall c \in \mathbb{R}$ by assumption.
Usually, it is less complicated to prove measurability by considering generators of $\mathcal{B}(\mathbb{R})$ rather than generic sets $A \in \mathcal{B}(\mathbb{R})$.