Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float to string with at least one decimal place (javascript)

Tags:

javascript

Let me give you an example.

var a = 2.0;
var stringA = "" + a;

I will get: stringA = "2", but I want: stringA = "2.0".

I don't want to lose precision however, so if:

var b = 2.412;
var stringB = "" + b;

I want to get the standard: stringB = "2.412".

That's why toFixed() won't work here. Is there any other way to do it, than to explicitly check for whole numbers like this?:

if (a % 1 === 0)
    return "" + a + ".0";
else
    return "" + a;
like image 266
Michał Avatar asked Feb 08 '15 01:02

Michał


2 Answers

There is a built-in function for this.

var a = 2;
var b = a.toFixed(1);

This rounds the number to one decimal place, and displays it with that one decimal place, even if it's zero.

like image 53
Niet the Dark Absol Avatar answered Sep 19 '22 19:09

Niet the Dark Absol


If you want to append .0 to output from a Number to String conversion and keep precision for non-integers, just test for an integer and treat it specially.

function toNumberString(num) { 
  if (Number.isInteger(num)) { 
    return num + ".0"
  } else {
    return num.toString(); 
  }
}

Input  Output
3      "3.0"
3.4567 "3.4567"
like image 28
jdphenix Avatar answered Sep 20 '22 19:09

jdphenix