Michał
Michał

Reputation: 2282

Convert float to string with at least one decimal place (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;

Upvotes: 26

Views: 83142

Answers (5)

kevinfjbecker
kevinfjbecker

Reputation: 101

This solution tries to balance terseness and readability

const floatString = (n) => Number.isInteger(n) ? n.toFixed(1) : n.toString();

Upvotes: 2

Michał
Michał

Reputation: 2282

For other people looking at this question, it just occurred to me, that to convert a float to a string with at least n decimal places, one could write:

function toAtLeastNDecimalPlaces(num, n) {
    normal_conv = num.toString();
    fixed_conv = num.toFixed(n);
    return (fixed_conv.length > normal_conv.length ? fixed_conv : normal_conv);
}

Note that according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed, toFixed() will work for at most 20 decimal places. Therefore the function above will not work for n > 20.

Also, the function above does not have any special treatment for scientific notation (But neither do any other answers in this thread).

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324730

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.

Upvotes: 34

Asheliahut
Asheliahut

Reputation: 911

If a is your float do

 var a = 2.0;
    var b = (a % 1 == 0) ? a + ".0" : a.toString();

Edited: add reference and change to allow for .0 http://www.w3schools.com/jsref/jsref_tostring_number.asp

Upvotes: 3

jdphenix
jdphenix

Reputation: 15435

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"

Upvotes: 24

Related Questions