Force float value when using JSON.stringify

前端 未结 2 1127
旧时难觅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.

    0 讨论(0)
  • 2021-01-12 05:45

    The straight and reasonably short answer to your question is no, you cannot customize the serialization of numeric values with JSON.stringify. See JSON.stringify() on MDN.

    If you really need decimals for your integers you have to use "regex-magic" as you mention in your question or find a library allowing you to perform such tricks. If you aren't dealing with overly complex or many different kinds of objects you could probably stringify them manually.

    As a sidenote, it sounds very, very suspicious with an API that needs to be fed with custom formatted JSON. I would tripple-check if there are any other way of using it.

    0 讨论(0)
提交回复
热议问题