TypeScript에서 문자열을 숫자로 변환하는 방법
하면 「」로 할 수 ?numberTypeScript 。
var numberString: string = "1234";
var numberValue: number = /* what should I do with `numberString`? */;
JavaScript와 마찬가지로 또는 함수를 사용하거나 단순히 unary를 사용할 수 있습니다.+★★★★★★★★★★★★★★★★★★:
var x = "32";
var y: number = +x;
기법은 (예: 10진수)을 합니다."123"다른 다양한 케이스(예상된 케이스)에 대해서는 다르게 동작합니다(예:"123.45" 케이스: " " 。null를 참조해 주세요.
이를 위한 Typscript 방법은 다음과 같습니다.
Number('1234') // 1234
Number('9BX9') // NaN
답변은 이쪽 https://stackoverflow.com/a/23440948/2083492 에서 확인할 수 있습니다.https://stackoverflow.com/a/23440948/2083492
동료 Angular 사용자의 경우:
템플릿 내에서Number(x) ★★★★★★★★★★★★★★★★★」parseInt(x) 에러가 발생하다.+x과가없없 없없없다다유효한 캐스팅은 다음과 같습니다.x*1 ★★★★★★★★★★★★★★★★★」x/1.
여기의 다른 답변에서 알 수 있듯이 변환에는 여러 가지 방법이 있습니다.
Number('123');
+'123';
parseInt('123');
parseFloat('123.45')
더 말씀드리겠습니다.parseInt★★★★★★★★★★★★★★★★★★.
「」를 사용하고 parseInt, 항상 기수 파라미터를 전달하는 것이 타당합니다.10진수 변환의 경우, 즉10이것은 파라미터의 디폴트값이기 때문에 생략할 수 있습니다.바이너리에서는2 ★★★★★★★★★★★★★★★★★」16열여섯 살사실, 2와 36 사이의 기수는 모두 사용할 수 있습니다.
parseInt('123') // 123 (don't do this)
parseInt('123', 10) // 123 (much better)
parseInt('1101', 2) // 13
parseInt('0xfae3', 16) // 64227
JS에서는 JS가parseInt 는 선행 0을 8진수로 해석합니다.
ECMAScript 3에서는 권장되지 않으며 ECMAScript 5에서는 금지되어 있지만 많은 구현에서는 선행0으로 시작하는 숫자 문자열을 8진수로 해석하고 있습니다.다음은 8진수 결과가 나올 수도 있고 10진수 결과가 나올 수도 있습니다.이 신뢰할 수 없는 동작을 방지하려면 항상 기수를 지정하십시오.
- MDN
코드가 명확해진다는 것은 기수 파라미터를 지정했을 때의 좋은 부작용입니다.
★★parseFloat는 기수 10의 숫자 표현식만 구문 분석하므로 여기서 기수 파라미터는 필요하지 않습니다.
자세한 내용은 이쪽:
Ryan이 말한 것을 설명하듯이, TypeScript는 일반적으로 JavaScript 숙어를 받아들인다.
var n = +"1"; // the unary + converts to number
var b = !!"2"; // the !! converts truthy to true, and falsy to false
var s = ""+3; // the ""+ converts to string via toString()
JavaScript Type Conversion의 모든 흥미로운 세부 정보.
문자열에서 숫자로 변환:
Typescript에서는 다음과 같은 방법으로 문자열을 숫자로 변환합니다.
parseInt(): 이개개 2 개개개 2 개 : : : : 。첫 번째는 해석할 문자열입니다.두 번째는 기수(예를 들어 10진수는 10, 2진수는 2 등)이다. 첫 할 수 합니다.NaN환됩니니다다parseFloat(): 해석할 값을 인수로 사용하여 부동소수점 번호를 반환합니다.할 수 없는 는, 「」를 참조해 주세요.NaN이 반환됩니다.+: 할 수 .연산자는 적절하게 사용할 경우 문자열 값을 숫자로 강제할 수 있습니다.
예:
/* parseInt */
// note that a whole number is returned, so it will round the number
console.log(parseInt('51.023124'));
// parseInt will 'cut off' any part of the string which is not a number
console.log(parseInt('5adfe1234'));
// When the string starts with non number NaN is returned
console.log(parseInt('z123'));
console.log('--------');
/* parseFloat */
// parses the string into a number and keeping the precision of the number
console.log(typeof parseFloat('1.12321423'));
// parseFloat will 'cut off' any part of the string which is not a number
console.log(parseFloat('5.5abc'));
console.log('--------');
/* + operator */
let myString = '12345'
console.log(typeof +myString);
let myOtherString = '10ab'
// + operator will not cut off any 'non number' string part and will return NaN
console.log(+myOtherString);
어떤 것을 사용할까요?
parseInt()문자열을 정수로 변환할 때 사용합니다.그러나 모든 숫자 값이 TS의 부동소수점 값이기 때문에 데이터 유형은 여전히 부동소수점입니다.또, 해석하는 번호의 기수를 지정할 필요가 있는 경우에도, 이 방법을 사용합니다.parseFloat()문자열을 부동소수점 번호로 해석해야 하는 경우.- .
+문자열을 부동소수점 번호로 강제하기 위한 연산자.이 방법의 장점은 구문이 매우 짧다는 것입니다.
가장 쉬운 방법은 +strVal 또는 Number(strVal)를 사용하는 것입니다.
예:
let strVal1 = "123.5"
let strVal2 = "One"
let val1a = +strVal1
let val1b = Number(strVal1)
let val1c = parseFloat(strVal1)
let val1d = parseInt(strVal1)
let val1e = +strVal1 - parseInt(strVal1)
let val2a = +strVal2
console.log("val1a->", val1a) // 123.5
console.log("val1b->", val1b) // 123.5
console.log("val1c->", val1c) // 123.5
console.log("val1d->", val1d) // 123
console.log("val1e->", val1e) // 0.5
console.log("val2a->", val2a) // NaN
다음 방법 중 하나를 따를 수 있습니다.
var str = '54';
var num = +str; //easy way by using + operator
var num = parseInt(str); //by using the parseInt operation
되어 있습니다.parseInt(),parseFloat() ★★★★★★★★★★★★★★★★★」Number()타이프 스크립트
=> convertstring 10 10 . 00 ' )을 사용하여 함수를 호출합니다.
parseFloat(string) => 부동, toFixed(4) => 소수점까지 변환하기 위해 사용할 수 있습니다.
parseInt(str) => 정수 변환에 사용할 수 있습니다.
convertstring(string){
let number_parsed: any = parseFloat(string).toFixed(4)
return number_parsed
}
const myNumber = 1200;
//convert to hexadecimal value
console.log(myNumber.toString(16)); //will return 4b0
//Other way of converting to hexadecimal
console.log(Math.abs(myNumber).toString(16)); //will return 4b0
//convert to decimal value
console.log(parseFloat(myNumber.toString()).toFixed(2)); //will return 1200.00
다른 형식을 10진수로 변환하는 방법에 대한 참고 자료
에서는, 「유형 정보」가 을 알 필요가 있습니다.var a.Number || String
export type StringOrNumber = number | string;
export function toString (v: StringOrNumber) {
return `${v}`;
}
export function toNumber (v: StringOrNumber) {
return Number(v);
}
export function toggle (v: StringOrNumber) {
return typeof v === "number" ? `${v}` : Number(v);
}
세 가지 방법이 있다
let a = + '12';
let b = parseInt('12' , 10); // 10 means decimal number
let c = Number('12');
다른 사람이 말한 대로 타입만을 말하는 경우 parseInt() 등은 올바른 타입을 반환합니다.또한 어떤 이유로든 값이 숫자 또는 문자열일 수 있으며 parseInt()를 호출하지 않을 경우 식 유형도 올바른 유형으로 캐스팅됩니다.
function f(value:number|string){
if(typeof value==='number'){
// value : number
}else {
// value : string
}
}
ionic 프로그래밍 상황에서는 데이터 타입을 변환하는 것이 어려운 경우가 많습니다.이것은 새로운 언어이기 때문에, 유저가 데이터 이온 타입을 문자열 데이터 타입 정수로 변환하는 방법에 대해 자세하게 설명합니다.
java, php, c, c++ 등의 프로그래밍 언어에서는...모두 데이터를 쉽게 이동할 수 있으며, 이온성에서는 데이터 변환도 쉽게 만들 수 있습니다. 다른 프로그래밍 언어에서도 마찬가지입니다.
this.mPosition = parseInt("");
다음은 StrToNumber 함수의 수정된 버전입니다.아까처럼
- 숫자 값의 앞 또는 뒤에 옵션 기호를 표시할 수 있습니다.
- 스트링의 선두 또는 후미에 기호가1개밖에 없는 것을 확인합니다.
- 오류가 발생하면 "passed" 기본값이 반환됩니다.
이 답변은 저의 이전 게시물보다 첫 번째 질문에 더 적합한 가능한 해결책입니다.
static StrToNumber(val: string, defaultVal:number = 0): number
{
let result:number = defaultVal;
if(val == null)
return result;
if(val.length == 0)
return result;
val = val.trim();
if(val.length == 0)
return(result);
let sign:number = 1;
//
// . obtain sign from string, and place result in "sign" local variable. The Sign naturally defaults to positive
// 1 for positive, -1 for negative.
// . remove sign character from val.
// Note, before the function returns, the result is multiplied by the sign local variable to reflect the sign.
// . error check for multiple sign characters
// . error check to make sure sign character is at the head or tail of the string
//
{
let positiveSignIndex = val.indexOf('+');
let negativeSignIndex = val.indexOf('-');
let nTailIndex = val.length-1;
//
// make sure both negative and positive signs are not in the string
//
if( (positiveSignIndex != -1) && (negativeSignIndex != -1) )
return result;
//
// handle postive sign
//
if (positiveSignIndex != -1)
{
//
// make sure there is only one sign character
//
if( (positiveSignIndex != val.lastIndexOf('+')) )
return result;
//
// make sure the sign is at the head or tail
//
if( (positiveSignIndex > 0) && (positiveSignIndex < nTailIndex ) )
return result;
//
// remove sign from string
//
val = val.replace("+","").trim();
}
//
// handle negative sign
//
if (negativeSignIndex != -1)
{
//
// make sure there is only one sign character
//
if( (negativeSignIndex != val.lastIndexOf('-')) )
return result;
//
// make sure the sign is at the head or tail
//
if( (negativeSignIndex > 0) && (negativeSignIndex < nTailIndex ) )
return result;
//
// remove sign from string
//
val = val.replace("-","").trim();
sign = -1;
}
//
// make sure text length is greater than 0
//
if(val.length == 0)
return result;
}
//
// convert string to a number
//
var r = +(<any>val);
if( (r != null) && (!isNaN(r)) )
{
result = r*sign;
}
return(result);
}
에서는 「」를 사용할 수 .as하다
var numberString: string = "1234";
const numberValue = numberString as number;
언급URL : https://stackoverflow.com/questions/14667713/how-to-convert-a-string-to-number-in-typescript
'programing' 카테고리의 다른 글
| AngularJS에서 HTTPS를 사용하려면 어떻게 해야 하나요? (0) | 2023.03.26 |
|---|---|
| 메타박스에서 WordPress 링크 삽입 대화 상자를 사용하시겠습니까? (0) | 2023.03.26 |
| json에서 대괄호를 사용하는 목적은 무엇입니까? (0) | 2023.03.26 |
| Karma 및 Jasmine을 사용한 각도 서비스에서의 '프라이빗' 기능 테스트 방법 (0) | 2023.03.26 |
| JDBC ResultSet 테이블 별칭이 있는 열을 가져옵니다. (0) | 2023.03.26 |
