简体   繁体   中英

AngularJS - disable float filtering

I'm creating a directive in AngularJs. Directive will receive from app controller a JSON object and based on that the directive will display the content.

I made a simple demo based on my problem that can be found at: http://jsfiddle.net/darkyndy/6StLm/

Now my JSON looks something like: ctrlItemJson = { myk: "something", state: { step: 1.0 } };

Why in directive-link, controller and view when I'm accessing state.step I get 1 instead of 1.0 ?

Setting value as string '1.0' it works, but for me I need to be exactly the same way how it was sent by the controller.

Later edit: This is mainly from Javascript as if you try var a = 1.0 and then try console.log(a) you will see 1

In this case for my issue I will discuss with API guys to send strings...

Solution :

1. In case you cannot control value:

For where you want to keep decimals (decimals are zeros, eg: 1.0 , 2.00 ) instead of using floats then use Strings (eg: '1.0' , '2.00' ).

2. In case you can control and know precision (directive will decide precision):

Then check responses for this question. Example: http://jsfiddle.net/SE5s3/

You can specify a certain float precision in JavaScript using .toPrecision(x) , where x is the precision you want.

Here's a version of your jsfiddle that implements this: http://jsfiddle.net/SE5s3/

The specific code I changed:

<input type="text" value="{{dyItemJson.state.step.toPrecision(2)}}"/>

This is not something AngularJS related, but rather JavaScript. For example,

var a = 2.0;

is actually just 2.

You can also use the number filter in Angular if you want your numbers to specific decimal places:

    template: '<input type="text" value="{{dyItemJson.state.step | number:2}}"/>',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM