Search code examples
pythonnumpyfloating-pointdigitsfractions

How can I pass the selective part of fraction number to string for displaying?


I would like to display the first 4 digit of fraction number and pass it to string to display in title of my plot. I checked this post but I couldn't find an elegant way.

I've tried following code as the easiest way the problem is I don't want to display % after that:

train_MSE=mean_squared_error(Y_train, Y_RNN_Train_pred)
print("Train MSE:",train_MSE_)
#Train MSE: 0.33068236552127656

train_MSE_ = "%.4f%%" % train_MSE
print("Train MSE:",train_MSE_)
#Train MSE: 0.3307% 
#expected result without '%' ---> 0.337

plt.plot(Y_RNN_Test_pred[0],'b-')
plt.title(f'Test MSE={test_MSE_}', fontsize=15, fontweight='bold')
plt.show()

Solution

  • You need to remove the %% at the end.

    train_MSE_ = "%.4f" % train_MSE_