2

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/

2 Answers 2

1

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)}}"/>

Sign up to request clarification or add additional context in comments.

2 Comments

For my case I cannot do this, as value is retrieved from an API and I'm "blind", meaning that I don't know if value is 1.0 or 1.00 or 1 :) So hardcoding precision doesn't work.
In that case, you have to get the value as a string. You can always count how many decimals you need from the string later.
0

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}}"/>',

1 Comment

Yes, you are right that is mainly from JS. Your solution may work for others, but for me it doesn't as I get that JSON from an API and I'm "blind", meaning that I don't know if value is 1.0 or 1.00 or 1 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.