user2413333
user2413333

Reputation: 1405

How to check if a number has two decimal places and keep the trailing zero if necessary?

If you have these numbers:

How can I do a check to see if the number has two decimal places?

If it has 2 decimals, how do you drop the second decimal number (rounding) but keep the trailing 0 if needed?

Examples of results:

2.05 would end in 2.1
2.04 would end in 2.0
2.54 would end in 2.5

I realise you can use toFixed(1), but that converts it to a string. And if you convert it to a int with parseInt(), it loses the trailing zero

Thanks guys

Upvotes: 3

Views: 15887

Answers (3)

David Schwartz
David Schwartz

Reputation: 182753

but toFixed turns it into a string, and if you use parseInt it gets rid of the trailing zero

You can have a number or you can have a representation of a number, but there is no third alternative.

If you want a representation of a number, what's wrong with a string? If you want a number, then there is no "trailing zero".

The number represented by "2.0" doesn't have a trailing zero because only representations can have trailing zeros. The number two can be represented with or without a trailing zero and it's the same number.

So: Do you want a number or a representation?

I think you must want a representation, because really only representation can have some specific number of decimal places. In that case, why isn't toString the right solution?

Upvotes: 2

David Thomas
David Thomas

Reputation: 253308

I'd suggest (the HTML upon which this is based follows):

$('li').text(function(i,t){
    var rounded = t.split('.')[1] ? (Math.round(parseFloat(t) * 10)/10).toFixed(1) : t;
    return t + ' (' + rounded + ')';
});

JS Fiddle demo.

The ternary:

t.split('.')[1] ? (Math.round(parseFloat(t) * 10)/10).toFixed(1) : t;

Assesses whether there's a period, if so then we parse the float to a number, multiply it by 10 (because we want the number to one decimal place), round that number and then divide it by ten and then, with toFixed(1) truncate the number to one (correctly-rounded) decimal place.

If there's no decimal portion to the number (it's an integer, not a float) we do nothing with it and simply use the existing number as it was found.

This is based upon the following HTML:

<ul>
    <li>2</li>
    <li>2.05</li>
    <li>2.547</li>
    <li>2.5</li>
    <li>2.04</li>
</ul>

Upvotes: 0

Ben S.
Ben S.

Reputation: 1143

Assuming that x is the value you are dealing with

var temp = Math.round(x * 10) / 10;   // This is the value as a number
document.write(temp.toFixed(1));      // writes the number in the desired format

In JavaScript, there is no distinction between the value 1.5 and the value 1.50 - as numbers, they are exactly the same. It is only when you convert them to a string, using something like toFixed(), that they become distinct.

Upvotes: 1

Related Questions