Force float value when using JSON.stringify

前端 未结 2 1126
旧时难觅i
旧时难觅i 2021-01-12 04:44

I want to force a Number to be a Float, after JSON.stringify(). Unfortunately JSON.stringify() deletes the 1 .0.

Example :

2条回答
  •  执笔经年
    2021-01-12 05:35

    Use toFixed instead of stringify. Example:

    var num = 1;
    var numStr = num.toFixed(1); //result is "1.0"
    

    More about toFixed - http://www.w3schools.com/jsref/jsref_tofixed.asp.

    To be clear We are talking about conversion number to string not number to float ( such type not exists in javascript ) like can be understood from question description. toFixed will always return String with specified number of decimals.

提交回复
热议问题