MrBuggy MrBuggy - 4 months ago 16
jQuery Question

Parse a floated number with parseFloat()

Hi I've got follow code:

keys = [
{ label: '1', key: '1' },
{ label: '2', key: '2' },
{ label: '3', key: '3' },
{ label: '4', key: '4' },
{ label: '5', key: '5' },
{ label: '6', key: '6' },
{ label: '7', key: '7' },
{ label: '8', key: '8' },
{ label: '9', key: '9' },
{ label: 'C', key: 'Delete' },
{ label: '0', key: '0' },
{ label: '.', key: '.' }
];


I loop my keys in an ng-repeat to build something like a calculator like this:

<div class="cKeys">
<div class="cKey" ng-repeat="item in ctrl.keys" ng-click="ctrl.modifyValue(item)">{{item.label}}</div>
</div>


When I click on a key, I call a function with the clicked object as parameter.

modifyValue(obj: any) {
let str = this.currentValue + obj.key;
this.currentValue = parseFloat(str);
}


In this function, I build a string and parse it with
parseFloat()
to get a number. The
this.currentValue
is an ng-model of an input, where my number should be displayed.

So when I click follow keys:
1
,
2
,
5
,
.
(the point) and
3
, I expect the number
125.3
in my input, but there is
1253
without the point? I thought, when I use the
parseFloat()
it should show me also floatet numbers. Whats wrong?

Answer

The '.' gets dropped as soon as it is appended, as parseFloat('125.') === 125.

Maintain two variables. One that contains the parsed result, and one that contains the concatenated string. Always parse the concatenated string:

modifyValue(obj: any) {
    this.concatStr += obj.key;
    this.currentValue = parseFloat(this.concatStr);
}

As @T.J. Crowder pointed out in the comments, this approach means that should you select the '.', it will not be "forgotten" if you then select another number after it.

Comments